简体   繁体   中英

How to get name of resource in terraform provider

I try to get the name of a resource as configured in HCL but need the value in my custom provider's go code.

resource "example_server" "bob" {
  name = "server"
}

In the golang code I want to use bob as value for d.SetId()

func resourceExsampleServerCreate(d *schema.ResourceData, meta interface{}) error {
  // do some stuff 
  d.SetId("bob")
}

The plan is to replace hardcoded value of bob with a variable;)

The name of a resource as given in the declaration header is for Terraform's own tracking and is not available to the provider code.

One big reason for this is that the name in question is not useful on its own: it is only useful in the context of the full resource instance address, which in this case would be example_server.bob but in more practical configurations could be something more complicated like example_server.bob[0] , module.foo.example_server.bob , module.foo["bar"].example_server.bob[15] , etc.

If the remote object type represented by example_server requires a unique name in the remote system , then the way to model that is to declare an argument for the resource (conventionally called name , but you can call it whatever makes sense for the system in question) and have the user choose what to set it to:

resource "example_server" "bob" {
  name = "bob"
}

The user might decide to set the two names the same as I showed above, but in real-world configurations that is rarely appropriate because name often belongs to a broader namespace in the remote system than the resource name in the Terraform configuration, and thus the user will want to set it to a name containing some additional context in order to ensure the appropriate amount of uniqueness to avoid collisions between separate configurations and separate modules within the same configuration.

If you'd like to use the name argument value as the id then you can just copy it over:

  d.SetId(d.Get("name"))

That's a common choice for representing objects in systems that don't assign surrogate keys to each object, and instead use the object's unique name as the sole identifier.

Terraform correlates the data you return with the full resource address in the saved state snapshot after each apply, so as a provider developer you don't need to worry about the resource address at all: Terraform will provide you whatever data you returned from the last operation so that you can use it to plan the next operation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM