TExcelTAD
Home › Infrastructure as Code: Terraform & OpenTofu › Importing Existing Infrastructure

Importing Existing Infrastructure

Most teams adopt infrastructure as code late: the VPC was clicked together in the console two years ago, the DNS zone was made by a script. Importing adds an existing object to state under a resource address, so from then on the code manages it, without destroying and recreating anything.

import blocks

The declarative way (Terraform 1.5+, OpenTofu 1.5+) is an import block: the target address and the provider-specific id of the real object. It is planned and reviewed like any other change, then applied:

hcl
import {
  to = aws_s3_bucket.assets
  id = "linkly-assets-prod"            # for S3 buckets the id is the bucket name
}

resource "aws_s3_bucket" "assets" {
  bucket = "linkly-assets-prod"
}

Each resource's registry page ends with an Import section giving the id format: a bucket name, vpc-0a1b2c…, sg-…, a role name, or a composite such as <zone_id>_<name>_<type> for Route 53 records.

Generating the configuration

Writing the matching resource block by hand is tedious for objects with dozens of arguments. plan -generate-config-out=FILE writes it for you from the imported attributes. The random provider supports import with ids you choose, so the whole flow runs here: random_integer takes "result,min,max" as its id.

bash · try it yourself
mkdir adopt && cd adopt
cat > main.tf <<'HCL'
import {
  to = random_integer.port
  id = "8080,8000,8999"
}
HCL
tofu init >/dev/null
tofu plan -generate-config-out=generated.tf | grep -v -E '^(Note|guarantee)'
echo "--- generated.tf"
cat generated.tf
tofu apply -auto-approve | tail -1
tofu plan | tail -1
random_integer.port: Preparing import... [id=8080,8000,8999]
random_integer.port: Refreshing state... [id=8080]

OpenTofu will perform the following actions:

  # random_integer.port will be imported
  # (config will be generated)
  # (imported from "8080,8000,8999")
    resource "random_integer" "port" {
        id     = "8080"
        max    = 8999
        min    = 8000
        result = 8080
    }

Plan: 1 to import, 0 to add, 0 to change, 0 to destroy.

Warning: Config generation is experimental

Generating configuration during import is currently experimental, and the
generated configuration format may change in future versions.

─────────────────────────────────────────────────────────────────────────────

OpenTofu has generated configuration and written it to generated.tf. Please
review the configuration and edit it as necessary before adding it to version
control.

--- generated.tf
# __generated__ by OpenTofu
# Please review these resources and move them into your main configuration files.

# __generated__ by OpenTofu from "8080,8000,8999"
resource "random_integer" "port" {
  keepers = null
  max     = 8999
  min     = 8000
  seed    = null
}
Apply complete! Resources: 1 imported, 0 added, 0 changed, 0 destroyed.
No changes. Your infrastructure matches the configuration.

Both CLIs still label configuration generation experimental, as the warning says. The generated block contains every argument, including the null ones. Treat it as a draft: delete the nulls and defaults, replace literal values with references and variables, move it into the right file, then plan until the plan shows only the import and no changes. An import plan that also says ~ update means your code and the real object disagree, and applying would change production.

When import is not possible

Not every resource type implements import. The local provider's local_file doesn't:

bash · try it yourself
mkdir no && cd no
printf 'hello\n' > existing.txt
cat > main.tf <<'HCL'
import {
  to = local_file.x
  id = "existing.txt"
}
resource "local_file" "x" {
  filename = "existing.txt"
  content  = "hello\n"
}
HCL
tofu init >/dev/null
tofu plan 2>&1 | grep -E 'Error|not support'
Error: Resource Import Not Implemented
This resource does not support import. Please contact the provider developer

For such resources the options are recreating the object under management, or leaving it unmanaged and reading it with a data source.

Importing at scale, and the old command

  • import blocks accept for_each (Terraform 1.7+, OpenTofu 1.7+), so you can import a whole map of buckets or users in one block:

    hcl
    import {
      for_each = var.legacy_buckets            # { assets = "linkly-assets", logs = "linkly-logs" }
      to       = aws_s3_bucket.this[each.key]
      id       = each.value
    }
  • The older CLI command tofu import ADDR ID writes to state immediately, without a plan or review, and one environment at a time. Prefer import blocks; once applied, you may delete them (or keep them as a record; an import block for an object already in state does nothing).

  • Tools such as terraformer and the cloud's own export features can generate configuration for whole accounts; expect to clean the output heavily.

A sample session against AWS, importing a hand-made bucket:

bash
$ tofu plan -generate-config-out=generated.tf
aws_s3_bucket.assets: Preparing import... [id=linkly-assets-prod]
aws_s3_bucket.assets: Refreshing state... [id=linkly-assets-prod]

OpenTofu will perform the following actions:

  # aws_s3_bucket.assets will be imported
  # (config will be generated)
    resource "aws_s3_bucket" "assets" {
        arn                         = "arn:aws:s3:::linkly-assets-prod"
        bucket                      = "linkly-assets-prod"
        bucket_regional_domain_name = "linkly-assets-prod.s3.eu-west-1.amazonaws.com"
        force_destroy               = false
        id                          = "linkly-assets-prod"
        region                      = "eu-west-1"
        tags                        = {}
        …
    }

Plan: 1 to import, 0 to add, 0 to change, 0 to destroy.

Test yourself

What does an import block need?

  1. Only the resource type
  2. The target address (to) and the provider-specific id of the existing object
  3. The object's ARN and a state file path
  4. A data source

Your import plan shows 1 to import, 0 to add, 1 to change. What should you do before applying?

  1. Apply: changes are expected
  2. Adjust the code until the plan shows only the import, unless the change is intended
  3. Run tofu refresh
  4. Delete the import block

What does -generate-config-out=generated.tf do?

  1. Exports the state
  2. Writes draft resource blocks for import targets that have no configuration yet
  3. Generates provider configuration
  4. Writes a plan file