Practitioners can use the terraform import command to let Terraform begin managing existing infrastructure resources. Resources can implement the ImportState method, which must either specify enough Terraform state for the Read method to refresh resource.Resource or return an error.
When the Read method requires a single attribute to refresh, use the resource.ImportStatePassthroughID function to write the import identifier argument for terraform import.
In the following example, the terraform import command passes the import identifier to the id attribute in Terraform state.
When the Read method requires multiple attributes to refresh, you must write custom logic in the ImportState method. Specifically, the implementation must:
Along with a resource.Resource implementation with the following Read method:
func(r exampleResource)Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse){var attrOne, attrTwo string
resp.Diagnostics.Append(req.State.GetAttribute(ctx, path.Root("attr_one"),&attrOne)...)
resp.Diagnostics.Append(req.State.GetAttribute(ctx, path.Root("attr_two"),&attrTwo)...)if resp.Diagnostics.HasError(){return}// API call using attrOne and attrTwo}
func(r exampleResource)Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse){var attrOne, attrTwo string resp.Diagnostics.Append(req.State.GetAttribute(ctx, path.Root("attr_one"),&attrOne)...) resp.Diagnostics.Append(req.State.GetAttribute(ctx, path.Root("attr_two"),&attrTwo)...)if resp.Diagnostics.HasError(){return}// API call using attrOne and attrTwo}
The terraform import command will need to accept both attribute values as a single import identifier string. A typical convention is to use a separator character, such as a comma (,), between the values. The ImportState method will then need to parse the import identifier string into the two separate values and save them appropriately into the Terraform state.
You could define the ImportState method using a comma-separated value as follows:
If the resource does not support terraform import, skip the ImportState method implementation.
When a practitioner runs terraform import, Terraform CLI will return:
$ terraform import example_resource.example some-identifier
example_resource.example: Importing from ID "some-identifier"...
╷
│ Error: Resource Import Not Implemented
│
│ This resource does not support import. Please contact the provider developer for additional information.
╵
$ terraform import example_resource.example some-identifier
example_resource.example: Importing from ID "some-identifier"...
╷
│ Error: Resource Import Not Implemented
│
│ This resource does not support import. Please contact the provider developer for additional information.
╵