Skip to content

Plannable Import: ID Interpolation #33228

@bondsb

Description

@bondsb

Terraform Version

Terraform v1.5.0-beta1
on darwin_amd64

Use 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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions