You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Terraform中GCP资源的引用方法及.name与.id属性的区别与适用场景咨询

Understanding When to Use .name vs .id for GCP Resources in Terraform

Great question—this is such a common sticking point when working with Terraform and GCP, especially since the docs don’t always call this out front-and-center. Let’s break this down clearly:

First, What Do .name and .id Actually Mean?

For most GCP Terraform resources:

  • .name is the short, human-readable name of the resource—this is usually the value you set in the name field of your resource block (or a generated name if you didn’t specify one explicitly). For your Pub/Sub topic, this would be my_topic.
  • .id is the full GCP resource identifier, formatted as projects/[your-project-id]/[resource-type]/[resource-name]. For your topic, that would look like projects/your-project-id/pubsub/topics/my_topic.

The Core Rule: Match the Parameter’s Required Format

There’s no universal list of "which resources use which"—it all depends on what the target resource’s parameter expects. Here’s how to figure it out:

  1. Check the Terraform Provider Docs: For the resource you’re configuring (e.g., google_pubsub_subscription or google_cloudiot_registry), look up the specific parameter you’re setting (like topic or pubsub_topic_name). The docs will explicitly state if it expects a short name or a full resource ID.
  2. Apply to Your Example:
    • For google_pubsub_subscription’s topic parameter: The docs note it accepts "the name of the topic"—but GCP and Terraform are flexible here; you can pass either .name or .id, and Terraform will resolve it correctly. Your use of .name works fine here.
    • For google_cloudiot_registry’s pubsub_topic_name parameter: The docs explicitly require "the full resource name of a Cloud Pub/Sub topic". That’s why you need to use .id here—using .name would throw an error because GCP can’t resolve the short name to a full topic path in this context.

Common Scenarios to Remember

  • Use .name when: The parameter asks for a simple, short resource name. Examples include referencing a Compute Engine instance’s name in a firewall rule, or a Cloud Storage bucket’s name in an IAM binding.
  • Use .id when: The parameter requires a full resource path. Examples include linking a Cloud Function to a Pub/Sub topic (the trigger_topic parameter), or setting a logging sink destination (which needs the full resource ID of a bucket/topic).

Pro Tip

If you’re ever unsure, you can run terraform plan and check the output—if you used the wrong attribute, Terraform will usually throw an error telling you it expected a full resource path (or vice versa). You can also inspect the state file (with terraform state show google_pubsub_topic.topic) to see exactly what values .name and .id hold for your resource.

内容的提问来源于stack exchange,提问作者Sekhar

火山引擎 最新活动