Terraform中GCP资源的引用方法及.name与.id属性的区别与适用场景咨询
.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:
.nameis the short, human-readable name of the resource—this is usually the value you set in thenamefield of your resource block (or a generated name if you didn’t specify one explicitly). For your Pub/Sub topic, this would bemy_topic..idis the full GCP resource identifier, formatted asprojects/[your-project-id]/[resource-type]/[resource-name]. For your topic, that would look likeprojects/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:
- Check the Terraform Provider Docs: For the resource you’re configuring (e.g.,
google_pubsub_subscriptionorgoogle_cloudiot_registry), look up the specific parameter you’re setting (liketopicorpubsub_topic_name). The docs will explicitly state if it expects a short name or a full resource ID. - Apply to Your Example:
- For
google_pubsub_subscription’stopicparameter: The docs note it accepts "the name of the topic"—but GCP and Terraform are flexible here; you can pass either.nameor.id, and Terraform will resolve it correctly. Your use of.nameworks fine here. - For
google_cloudiot_registry’spubsub_topic_nameparameter: The docs explicitly require "the full resource name of a Cloud Pub/Sub topic". That’s why you need to use.idhere—using.namewould throw an error because GCP can’t resolve the short name to a full topic path in this context.
- For
Common Scenarios to Remember
- Use
.namewhen: 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
.idwhen: The parameter requires a full resource path. Examples include linking a Cloud Function to a Pub/Sub topic (thetrigger_topicparameter), 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




