-
Notifications
You must be signed in to change notification settings - Fork 10.3k
Plannable Import: ID Interpolation #33228
Description
Terraform Version
Terraform v1.5.0-beta1
on darwin_amd64Use Cases
Interpolation of the import block id enables more complex import scenarios, allowing the user to specify identifiers through variables or other known values at plan time.
This feature enables easier import solutions for
- Pipelines
- Terraform Cloud
- Self-Service Solutions
It also provides a mechanism for automatic import, or "import-if-not-exists".
Attempted Solutions
The plannable import feature currently limits the value of the import block id to a constant string value. The following code snippet is not allowed:
resource "aws_instance" "web" {
...
}
import {
to = aws_instance.web
id = var.web_instance_id # FAILS
}Proposal
This proposal is an extension of the plannable import feature which is planned for inclusion in Terraform 1.5.
In this feature, the identifier may be specified by any interpolation that can be resolved at plan time. In this example (the same as the above example), we are now allowed to use a variable for an AWS instance ID:
resource "aws_instance" "web" {
...
}
import {
to = aws_instance.web
id = var.web_instance_id # allowed now
}The import block is ignored if id is null and a new resource will be created. Conditional import with variables makes it easier to import resources using pipelines or Terraform Cloud.
Automatic Import (import-if-not-exists)
For this scenario, we would like to import a web server if it exists or create a new one if it doesn't. The cloud provider creates a new ID every time we rebuild our infrastructure. But we know that the server will always be named "webserver1".
Let's use use a data source to check whether "webserver1" exists:
data "aws_instance" "existing_server" {
filter {
name = "tag:Name"
values = ["webserver1"]
}
}and import it only if it does:
resource "aws_instance" "web" {
...
}
import {
to = aws_instance.web
id = try(data.aws_instance.existing_server.id, null) # if the server doesn't exist, create a new one
}References
- Plannable import 3: Make import plannable #33085 (comment)
- Automatic Import Using Identifier Specification #27959
- Support import blocks in config #31910 (comment)
- Persistent state and automatic reimport for resources that aren't fully deleted on
destroy#33216 - Import by declarative code over imperative command #26364