DEV Community

DevOps Job Updates
DevOps Job Updates

Posted on Originally published at devopsjobupdates.com

Terraform Import Tutorial: Bring Existing Resources Under Management

Almost every team that adopts Terraform inherits infrastructure that was built by hand: a bucket created in the console during an incident, a database provisioned years ago, a virtual network nobody dares to touch. The choice is not between managing it with Terraform or leaving it alone — it is between importing it properly and rebuilding it, with the downtime and risk that rebuilding brings. Terraform import is the tool that moves existing resources under Terraform management without recreating them.

This tutorial covers both ways to import: the classic terraform import command and the modern import block, which is the approach you should use for anything that goes through review. You will import a real S3 bucket, generate configuration from the live resource, import a whole set of resources at once, and fix the errors that appear when the import does not go to plan. The examples use AWS, but the mechanics are identical on Azure and GCP — only the resource IDs change.

What Terraform Import Does (and Does Not Do)

Import does one thing: it records an existing cloud resource in Terraform's state file, mapping a resource address in your configuration to the real object in the cloud. After an import, Terraform knows the resource exists, and the next plan compares your configuration with the live resource instead of proposing to create it. Import does not create the resource, does not delete it, and — in the classic form — does not write any configuration for you. That last point surprises beginners: after a classic import, you still have to write the resource block yourself, and until the configuration matches the live resource, Terraform will propose changes.

Import is also deliberately limited. The command imports one resource at a time, and it cannot import an entire collection — such as a whole VPC with its subnets, route tables and gateways — in a single operation. Each resource is imported individually, which is slow for a large estate and is exactly why the bulk techniques in the later sections exist. Import also assumes that each remote object is bound to only one resource address. Importing the same object twice, under two different addresses, produces behaviour Terraform's own documentation warns against, because two parts of your configuration will then fight over one real object.

Before you import anything, protect the state. Import writes directly to the state file, so a mistake can corrupt the record of your whole environment. Back the state up first — with a remote backend such as S3, enable versioning on the state bucket so you can restore a previous version; with a local backend, copy the state file before you begin. Our Terraform state explained guide covers backends, locking and recovery in detail, and it is worth reading before you run your first import against a production state file. If you are new to Terraform entirely, start with our Terraform tutorial for beginners, which builds a working configuration from scratch before any of the import mechanics in this guide.

The Classic terraform import Command

The classic workflow has three steps: write a resource block for the existing resource, run the import command, and then run a plan to align the configuration with reality. The resource block can be nearly empty to start with — Terraform only needs the address to exist — and you fill in the arguments after the import, using the plan output to tell you what is missing.

Suppose a bucket called acme-prod-assets was created in the console and now needs to be managed by Terraform. First, declare it:

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "eu-west-1"
}

resource "aws_s3_bucket" "assets" {
  # Arguments will be filled in after the import.
}
Enter fullscreen mode Exit fullscreen mode

Then import it. The command takes the resource address and the ID Terraform's provider uses to find the object — for an S3 bucket, the ID is simply the bucket name; for an EC2 instance it is the instance ID; for a Route 53 zone it is the zone ID. The ID format depends on the resource type, so check the provider's documentation for each resource you import rather than guessing.

terraform init
terraform import aws_s3_bucket.assets acme-prod-assets
Enter fullscreen mode Exit fullscreen mode

HashiCorp's own documentation describes this flow in Import existing resources: write the resource block, run the command, and then run a plan to see how the configuration compares with the imported resource. The plan after an import is the moment of truth. It will usually propose changes, because your empty resource block does not yet describe the live bucket — its tags, its versioning, its encryption. Add the arguments one at a time and re-run the plan until it reports no changes. When the plan is clean, the import is complete: Terraform manages the bucket, and the next apply will change nothing.

The classic command's weakness is that it writes state immediately, with no preview. There is no plan step before the state changes, no pull request to review, and no easy undo beyond restoring a state backup. That is acceptable for a single resource in a development account. For production, or for anything a teammate should review, the import block is the better tool — and it is the subject of the next section.

One more worked example, because a second resource type shows how the ID changes while the workflow stays the same. An EC2 instance is imported by its instance ID, and its security group by its group ID, each in its own command:

resource "aws_instance" "web" {
  # Fill in ami, instance_type and tags after the import.
}

resource "aws_security_group" "web" {
  # Fill in ingress and egress rules after the import.
}
Enter fullscreen mode Exit fullscreen mode
terraform import aws_instance.web i-0123456789abcdef0
terraform import aws_security_group.web sg-0123456789abcdef0
terraform plan
Enter fullscreen mode Exit fullscreen mode

The plan will propose changes for both resources, because the empty blocks do not yet describe them. Fill in the arguments from the live resources — the AMI ID, the instance type, the security group's ingress and egress rules — and re-run the plan until it is empty. Notice the order matters here: the instance references the security group, so import the security group first and add the reference to the instance block, otherwise the plan will propose replacing the instance to attach a group it does not yet know about. When two resources depend on each other, import the dependency first.

Import Blocks: The Modern, Reviewable Way

Import blocks, available since Terraform 1.5, move the import into your configuration, where it can be reviewed like any other change. An import block maps a resource address to a cloud ID, and Terraform processes it during the next plan, so the import itself goes through the same review and approval flow as the rest of your infrastructure changes.

import {
  to = aws_s3_bucket.assets
  id = "acme-prod-assets"
}

resource "aws_s3_bucket" "assets" {
  # Arguments will be filled in after the import.
}
Enter fullscreen mode Exit fullscreen mode

Run a plan and Terraform imports the bucket into state as part of the plan, then shows you the configuration drift between your resource block and the live bucket. Nothing is applied until you approve the apply, which means the import is visible in the pull request before it touches anything. When the import is done and the configuration matches, remove the import block — it is a one-time instruction, not a permanent part of the configuration — and leave the resource block behind.

Import blocks also solve the problem of importing into modules. If the bucket belongs inside a module, the to address includes the module path:

import {
  to = module.storage.aws_s3_bucket.assets
  id = "acme-prod-assets"
}
Enter fullscreen mode Exit fullscreen mode

And for a resource created with for_each or count, the address includes the specific instance key, such as aws_s3_bucket.assets["prod"] or aws_s3_bucket.assets[0]. Getting that address wrong is the most common import-block error: Terraform will tell you the address does not match any resource in the configuration, and the fix is to copy the address from the plan output rather than typing it from memory.

Generating Configuration with -generate-config-out

The most tedious part of an import is writing the resource block to match a live resource you did not create. Terraform can do that for you. When you run a plan with -generate-config-out, Terraform reads the imported resource and writes a generated configuration file containing the arguments it discovered:

terraform plan -generate-config-out=generated.tf
Enter fullscreen mode Exit fullscreen mode

The generated file is a starting point, not a finished product. It contains everything Terraform could read from the live resource, including arguments you would never write by hand — computed values, default settings, and attributes that are only relevant to the provider's internal bookkeeping. Your job is to move the meaningful parts into your real configuration files, delete the noise, and remove the generated file. A typical clean-up pass removes read-only attributes, replaces hard-coded values with variables where the value should vary by environment, and adds the tags and lifecycle rules your team standardises on.

Work through the generated file with the plan as your guide. After you move the cleaned configuration into place and delete the import block, run a plan: if it shows no changes, the generated configuration matches reality. If it shows changes, read them carefully — they are usually a missing argument, such as a bucket's versioning status or a security group's description, and the fix is to add that argument to the resource block. Repeat until the plan is empty. That empty plan is the definition of a finished import, and it is worth insisting on: a plan that still shows changes after an import means Terraform will try to apply those changes on the next run, which may modify a production resource you only meant to adopt.

One caution about generated configuration: it reflects the resource as it is, not as it should be. If the bucket you imported has no encryption and no versioning, the generated configuration will faithfully reproduce that — and your plan will be clean while your security posture stays weak. Treat the import as the moment to fix the resource, not just to adopt it: add the encryption block, enable versioning, and let the next apply improve the resource rather than merely preserving it. The same caution applies to secrets. Generated configuration can contain values that should never be committed — a database password captured in a resource argument, or an access key embedded in a user-data script. Read the generated file line by line before it enters source control, move any secret into a variable backed by a secrets manager or a secure variable store, and check the file into version control only after that review. A generated file that is committed without review is how credentials end up in a repository.

Importing at Scale: for_each and Bulk Imports

Importing one bucket by hand is fine. Importing forty is not, and this is where import blocks earn their keep. Since Terraform 1.7, an import block itself accepts for_each, so a single block can import a whole set of resources from a map of names to IDs:

locals {
  buckets = {
    prod    = "acme-prod-assets"
    staging = "acme-staging-assets"
    dev     = "acme-dev-assets"
  }
}

import {
  for_each = local.buckets
  to       = aws_s3_bucket.this[each.key]
  id       = each.value
}

resource "aws_s3_bucket" "this" {
  for_each = local.buckets
  bucket   = each.value
}
Enter fullscreen mode Exit fullscreen mode

Generate the map from the cloud rather than typing it by hand. A short script that lists resources through the provider's CLI — aws s3api list-buckets, for example — and writes the import blocks is faster and less error-prone than forty copy-paste operations, and it can be re-run when the estate changes. Keep the script in the repository next to the configuration, so the next person who inherits the estate can see how the imports were produced. A minimal version for S3 looks like this:

#!/bin/bash
# Generate one import block per bucket whose name starts with acme-.
# Review the output before running any plan: generated code is a draft.
set -euo pipefail

{
  echo 'locals {'
  echo '  buckets = {'
  aws s3api list-buckets \
    --query "Buckets[?starts_with(Name, \`acme-\`)].Name" \
    --output text | tr '\t' '\n' | while read -r bucket; do
      key=$(echo "$bucket" | sed 's/^acme-//; s/-assets$//')
      echo "    $key = \"$bucket\""
  done
  echo '  }'
  echo '}'
  echo ''
  echo 'import {'
  echo '  for_each = local.buckets'
  echo '  to       = aws_s3_bucket.this[each.key]'
  echo '  id       = each.value'
  echo '}'
} > imports.tf

echo "Wrote imports.tf — review it, then run terraform plan."
Enter fullscreen mode Exit fullscreen mode

That script shows the pattern rather than a finished tool: list the resources, derive a key for each one, and emit the block. In practice you will adapt it to the resource type — EC2 instances need their IDs, not their names — and you will review every line of generated output before it reaches a plan, because a script that imports the wrong resource is worse than typing slowly. For a one-off migration, a script you run once and delete is fine; for an estate that keeps growing outside Terraform, the script belongs in the repository as a maintained tool.

For very large estates, HCP Terraform offers a search-and-import feature that discovers resources across your cloud providers through a visual query builder or through list blocks in configuration, then generates the configuration for the resources you select. It needs a workspace running Terraform 1.14 or newer, and it is the right tool when the estate is too large to enumerate by hand. The HCP documentation, Search and import resources, sets out the workflow and its requirements, including the note that policy evaluation against query results needs Terraform 1.17.0 or later. As of this writing the current release is Terraform 1.17.2, released 11 November 2026, so a workspace on the current version meets both requirements.

Whatever the scale, import in waves, not all at once. Import one resource type — buckets first, then the roles that use them — and get a clean plan for each wave before starting the next. A clean plan per wave localises failures: when something goes wrong, you know which wave introduced it. Importing everything at once and then debugging a plan with hundreds of proposed changes is how a migration stalls for a week.

Modules, Count and Tricky Resource IDs

Real estates are rarely flat, and imports get harder as the configuration gets more structured. Resources inside modules need module-prefixed addresses, resources with count need an index, and resources with for_each need a key. The address syntax is the same one Terraform uses everywhere — module.storage.aws_s3_bucket.assets, aws_instance.web[0], aws_s3_bucket.this["prod"] — but it must match the configuration exactly, including the module path and the key type. A string key in quotes and a number index without quotes are different addresses, and Terraform will reject the wrong one.

Resource IDs are the second trap. The ID format is defined by the provider, not by Terraform, and it varies by resource: a bucket uses its name, an EC2 instance uses its instance ID, a Route 53 zone uses the domain name, and a security group rule uses a composite ID that combines the group and the rule. Some resources have IDs that are not obvious from the console, and a few cannot be imported at all — the provider's documentation for each resource states whether import is supported and what ID format it expects. When an import fails with an error about the ID, the provider documentation for that resource is the first place to look, not the Terraform CLI documentation.

Complex imports are a third complication. Some resources import secondary resources along with them: importing an AWS network ACL, for example, also imports one aws_network_acl_rule for each rule it contains. Those secondary resources land in state without a corresponding resource block, and if you do not add blocks for them, Terraform will plan to destroy them on the next run. Always read the import output for a mention of secondary resources, and add a block for each one before you run your next plan.

Our Terraform modules tutorial covers the module patterns that make large imports manageable — one module per resource type, composition through outputs — and it is the natural next step once the resources are under management and you need to organise them.

Common Errors and How to Fix Them

Most import failures fall into a small set of patterns, and each has a clear fix. "Cannot import non-existent remote object" means the ID is wrong, the resource is in a different Region or account than your provider is configured for, or the resource was already deleted. Check the provider configuration first — the wrong Region is the most common cause — then verify the ID with the cloud CLI before retrying.

"Resource already managed by Terraform" means the object is already in state under a different address. Find it with terraform state list, and move it to the right address with terraform state mv instead of importing it a second time. Importing the same object twice is exactly the situation Terraform warns against, and the state move command is the correct remedy.

A plan that proposes to destroy the resource you just imported means the configuration does not describe it, or the resource block is missing entirely. With the classic command, this happens when you import and then forget to write the block; with import blocks, it happens when the generated configuration was deleted before being moved into the real files. Write the block, re-run the plan, and the destroy should disappear.

A plan that proposes to replace the resource — destroy and recreate — is more serious, because applying it would delete the live object. Replacement is proposed when an argument that forces recreation differs between the configuration and the live resource, such as a bucket name or a database engine version. Find the differing argument in the plan output, set it to the live value, and the replacement should become an update or disappear. Never apply a plan that replaces a production resource you only meant to adopt.

Finally, a state lock error during an import means another Terraform process holds the lock — usually a colleague's run, or a crashed process that never released it. Do not force-unlock a lock you do not understand: check who holds it, and only use terraform force-unlock when you are certain no other process is running. A forced unlock during a concurrent write is how state files get corrupted.

Two state commands round out the toolkit. terraform state mv renames or relocates a resource in state without touching the cloud, which is how you fix an import that landed at the wrong address, or move a resource into a module after the fact:

terraform state list
terraform state mv aws_s3_bucket.assets module.storage.aws_s3_bucket.assets
terraform state mv 'aws_s3_bucket.this["prod"]' 'aws_s3_bucket.this["production"]'
Enter fullscreen mode Exit fullscreen mode

terraform state rm removes a resource from state without destroying it in the cloud — the opposite of import, and the right command when something was imported by mistake or when a resource should leave Terraform management but keep running. And if you need to stop managing a resource permanently through configuration rather than a command, the removed block, available since Terraform 1.7, declares that a resource should be removed from state on the next apply, without destroying it. All three commands edit state directly, so back the state up before you run any of them, exactly as you did before the import itself.

Frequently Asked Questions

Does terraform import change or recreate the resource?

No. Import only records the existing resource in Terraform's state file. It does not modify, delete or recreate anything in the cloud. Changes only happen later, when you apply a plan that proposes them.

What is the difference between terraform import and an import block?

The command writes state immediately, generates no configuration, and has no plan step, so you must write the resource block by hand first. An import block, available since Terraform 1.5, goes through the plan, can generate configuration with -generate-config-out, and sits in a pull request for review before anything touches state.

Can I import a whole VPC at once?

No. Terraform imports one resource at a time, and it cannot import an entire collection such as a VPC with its subnets and route tables in a single operation. Import each resource individually, or use for_each on an import block, or HCP Terraform's search-and-import for large estates.

What should I do with the import block after the import?

Remove it. The import block is a one-time instruction: once the resource is in state and the configuration matches, the block has done its job. Leaving it in place causes Terraform to try the import again on the next plan.

Why does Terraform want to destroy the resource I just imported?

Because the resource exists in state but there is no matching resource block in the configuration. Terraform reads that as "this object should not exist" and plans to destroy it. Add the resource block, run a plan, and the destroy should disappear.

Conclusion

Import is how Terraform meets reality: the infrastructure you already have, built by hand over years, brought under management without downtime. Use import blocks for anything that deserves review, generate configuration from the live resource instead of typing it from memory, clean the generated output before you commit it, and insist on an empty plan before you call the import done. Import in waves, back up state before you start, and fix the security gaps the import reveals rather than preserving them. Do that, and the estate you inherited becomes an estate you can change with confidence — which is the whole point of infrastructure as code.

Top comments (0)