The terraform import command brings existing infrastructure under Terraform management by writing it into state. On Terraform 1.5 and later, declare an import block, run terraform plan -generate-config-out=generated.tf to draft the resource configuration, review the plan, then apply. The older CLI command still works, but it writes state immediately, with no plan and no dry run.

This Terraform import example is chapter 2 of our Terraform best practices guide. Import binds a real object to Terraform state but does not verify that your configuration matches that object. The danger surfaces at the next apply: if your configuration disagrees with reality, Terraform changes real infrastructure to match the code, potentially destroying or recreating resources. On Terraform 1.5 and later, import blocks provide a reviewable path, while the CLI command remains necessary on earlier versions.

What terraform import does

An import writes a record into Terraform state that binds a resource address in your configuration to a real object in your cloud account. It does not create the configuration, and it does not check that your configuration describes the object accurately.

Terraform reconciles your declared configuration with two records of reality: the state it tracks and the infrastructure that exists. Import aligns state with infrastructure and leaves the config entirely to you, which is why most post-import errors trace back to a resource block that someone guessed rather than verified.

Since Terraform 1.5, terraform plan -generate-config-out can draft configuration, which removes the guessing but not the review. The most common trigger is a ClickOps estate: resources teams built in the console over the years and now need under version control.

Common reasons to import resources

Imports rarely happen for their own sake. They show up attached to one of these situations:

SituationWhat the import accomplishes
ClickOps to IaC migrationConsole-built resources move into state and version control, one dependency chain at a time
Team handoffsInfrastructure another team built becomes manageable by yours without recreating it
Disaster recoveryTerraform reconnects resources that a team restored or rebuilt outside Terraform to the state file
Environment cloningA team imports and codifies an existing environment as a parameterized template

Which import method should you use?

Use import blocks unless you are pinned below Terraform 1.5. HashiCorp introduced the import block in Terraform 1.5, released June 2023, making an import a declared, plannable action that you review before state changes.

The same release added -generate-config-out, which writes a draft resource block for each imported object. The CLI command predates both, still works on supported Terraform releases, and remains the option on versions below 1.5, but it mutates state the moment you press enter.

Here is how the two methods compare:

CriterionDeclarative import blockterraform import CLI
Terraform version required1.5+ (for_each on blocks from 1.7); -generate-config-out also requires 1.5+Any
Reviewable plan firstYesNo
Writes state immediatelyNo, only at applyYes
Config generationYou write the resource block, or -generate-config-out drafts a resource block per importNo
Works in CIYes, imports appear in plan output for review, but a generated file needs a human passPoorly, no plan step to gate on
Multiple resources per operationYes, many blocks per apply, but config generation cannot be combined with for_each blocksOne resource per invocation

Two caveats belong next to that recommendation. HashiCorp’s documentation still labels configuration generation experimental, and later minor versions may change the generated formatting, so treat the output as a draft. Confirm your own binary’s version before relying on newer conveniences. Terraform 1.6 added expressions in the id field; support for for_each on import blocks followed in 1.7. As of September 2026, current releases sit at 1.16.

Terraform import prerequisites

An import needs four things in place, whichever path you take:

  • A Terraform version that matches the method: 1.5 or later for import blocks and config generation, anything for the CLI.
  • Provider credentials with read access: Terraform reads the object’s full attribute set from the provider API during the import.
  • The resource ID in the provider’s expected format: For AWS this is the native object ID, such as i-01aeed690c9fb5322 for an instance.
  • A destination for the import: An import block on the declarative path, or a hand-written resource block on the CLI path.

That last item trips up most mid-import readers. If you run the CLI command without a matching resource block, Terraform returns this exact error:

Error: resource address "aws_instance.foo" does not exist in the configuration.

Before importing this resource, please create its configuration in the root module. For example:

resource "aws_instance" "foo" {
  # (resource arguments)
}

Write the stub, then rerun the command. Import blocks with config generation avoid this error because Terraform generates the resource block.

How to import an EC2 instance with an import block

The workflow follows four steps:

  1. Declare the import.
  2. Generate the configuration.
  3. Review the plan.
  4. Apply the import.

Start with the block itself in any .tf file:

import {
  to = aws_instance.web
  id = "i-01aeed690c9fb5322"
}

Then run the plan with config generation. The output file must not already exist:

terraform plan -generate-config-out=generated.tf

The plan output flags the instance with # aws_instance.web will be imported and a (config will be generated) note, and the summary line gains an import count, in the form Plan: 1 to import, 0 to add, 0 to change, 0 to destroy. Nothing has touched state yet.

Review and clean up generated.tf before running terraform apply. The apply writes the binding into state. You can delete the import block afterward, though HashiCorp’s import block guidance recommends keeping it as a historical artifact; the block is idempotent and will not re-import a resource that is already in state.

Find the resource ID the provider expects

For aws_instance, the ID is the EC2 instance ID visible in the console under Instances, or via the CLI:

aws ec2 describe-instances \
  --filters "Name=instance-state-name,Values=running" \
             "Name=tag:Name,Values=YOUR_INSTANCE_NAME" \
  --query 'Reservations[*].Instances[*].InstanceId' \
  --output text

The same describe-instances call returns the instance’s image-id, which you will want when checking the AMI in your config. If your configuration selects the latest Amazon Linux 2023 image with a data source, verify what that filter currently resolves to:

aws ec2 describe-images \
  --owners amazon \
  --filters "Name=name,Values=al2023-ami-*-x86_64" \
  --query 'sort_by(Images, &CreationDate)[-1].ImageId' \
  --output text

If the imported instance runs an older image than the filter returns, Terraform will plan to replace the instance.

terraform plan -generate-config-out produces a draft, not finished code

The generated file contains a resource block with every non-sensitive attribute Terraform read from the provider. Expect to fix several things before committing it:

  • Hard-coded IDs and ARNs: Generation emits literals like subnet_id = "subnet-0ab..." rather than references such as aws_subnet.main.id, so no dependency graph exists until you add the references yourself.
  • Sensitive attributes as null: Passwords and secrets come through as null and need variable or secrets-manager references.
  • Default values written verbatim: Attributes like ebs_optimized = false match provider defaults and can be removed.
  • Conflicting argument pairs: Generation can emit conflicting arguments, which fail the plan until you delete one.

Run terraform fmt, then iterate on terraform plan until it reports no changes.

The legacy terraform import command writes state with no plan

The CLI form takes a resource address and a provider ID as positional arguments:

terraform import aws_instance.web i-01aeed690c9fb5322

The address, aws_instance.web, must match a resource block you already wrote. The ID, i-01aeed690c9fb5322, is the provider-native identifier.

HashiCorp’s 1.5 announcement puts it plainly: “State is immediately modified, with no opportunity to preview the results.” That can lead to accidental modifications or deletions if a teammate applies against the shared state before your configuration catches up.

The command also handles one resource per invocation, so a six-resource chain means six commands, each an immediate state mutation. It demonstrates the mismatch failure vividly, because the moment the command finishes, your hand-written stub is bound to a real object, and every attribute you guessed wrong is now a pending change.

What a mismatched configuration does to your infrastructure

After an import, the next terraform plan compares your configuration against the freshly imported state, and the next terraform apply acts on whatever it finds. Whether a mismatched attribute updates in place or destroys the resource depends on whether the AWS provider marks it ForceNew.

  • instance_type mismatch: A wrong instance_type shows as ~, an in-place update, but the apply is not free. The provider stops the instance before changing its type, then starts it again, which means a reboot. During that stop, AWS applies documented stop/start side effects: AWS erases instance-store data and releases the auto-assigned public IPv4 address. Elastic IPs persist, because the instance retains its private IPv4 address. In-place resizing also requires an EBS-backed instance with a compatible target type, and from AWS provider v5.43.0, a type change that crosses CPU architectures, x86_64 to arm64 for instance, forces replacement instead.
  • ami mismatch: A wrong ami has more destructive consequences. The attribute is ForceNew in the provider schema, so the plan shows -/+ with # forces replacement on the ami line, and import-block plans add # Warning: this will destroy the imported resource. Apply that plan and Terraform terminates the instance you imported and launches a new one. This is how a data source pointed at the latest al2023-ami-*-x86_64 image quietly schedules the destruction of an instance running last quarter’s AMI.

Read each attribute under a ~ or -/+ marker as a disagreement between your code and reality. For each value you intend to keep as-is, copy the real value into the configuration and rerun the plan until you see “No changes. Your infrastructure matches the configuration.”

Reserve ignore_changes for attributes an external process legitimately owns, such as tags a governance agent writes. It suppresses update planning only, while Terraform still refreshes the real values in state. Because ignore_changes = all leaves the resource effectively unmanaged, using it to silence a diff you have not understood just defers the surprise.

Map related resources before importing

After importing one console-built instance, you may find related resources that also require import.

One instance pulls in five more:

  1. The instance itself.
  2. The security group you also built by hand — import it before the config references it.
  3. The VPC that contains the security group, if you intend to manage it — import it before replacing its hard-coded ID with a Terraform reference.
  4. The RDS database the application writes to.
  5. The instance profile the instance runs under.
  6. The IAM role that profile wraps.

This cascade is why the planning step matters more than the command syntax. Map the object graph and decide where the managed boundary sits before you import anything, because a reference that crosses the boundary either becomes a hard-coded ID or another import.

Import blocks change the mechanics of that plan. You can declare all six objects as import blocks and land the entire chain in one reviewed apply, rather than six sequential CLI mutations.

Import multiple resources in one apply

Multiple import blocks in one configuration produce one plan and one apply, and from Terraform 1.7 an import block accepts for_each, so a map of bucket names can drive a whole family of imports. One limitation to plan around: -generate-config-out has a documented incompatibility with for_each, and it is wider than it first looks: config generation is refused for import blocks that use for_each and for target resources that use for_each or count. Terraform says so outright:

The given import block is not compatible with config generation. The -generate-config-out option cannot be used with import blocks which use for_each, or resources which use for_each or count.

Generate config for a single representative resource, then write the for_each version by hand.

For migrations too large to hand-declare, Microsoft’s aztfexport can emit native import blocks with --generate-import-block for Azure estates, so its output feeds the standard 1.5+ workflow.

Terraform import into a module

Prefix a module resource’s full address with its module path:

import {
  to = module.network.aws_vpc.main
  id = "vpc-a01106c2"
}

The destination resource block must exist inside the module’s source, and nested modules stack the path, module.parent.module.child.aws_vpc.main. The CLI accepts the same addresses, terraform import module.network.aws_vpc.main vpc-a01106c2, with one shell trap: indexed addresses contain brackets, which bash and zsh treat as glob patterns, so quote them. The documented form is terraform import 'aws_instance.baz[0]' i-abcd1234, and for_each keys keep their inner double quotes, as in 'module.vpc["us-east-1"].aws_vpc.main'.

How to undo a terraform import

The undo paths here edit Terraform’s records without changing the cloud object. Which one applies depends on how far you got:

  • Import block, not yet applied: Delete the block. State only changes at apply, so nothing has happened.
  • Already in state: terraform state rm aws_instance.web follows the state removal docs and removes the binding without destroying the object. Know the follow-on: the next plan will propose creating a new object for the still-present resource block, and that create can fail if names collide with the real one, so remove or fix the config in the same change.
  • Right resource, wrong address: terraform state mv follows the state move docs and rebinds the object to a new address without recreating it, useful when the import landed at aws_instance.temp and belongs at module.web.aws_instance.main.
  • Terraform 1.7+: A removed block with lifecycle { destroy = false } provides the removed block guidance for a plannable equivalent of state rm, reviewable in a plan like the import was.

With local state, Terraform keeps the previous version in terraform.tfstate.backup; remote backends do not write local copies, so pull a copy with terraform state pull before surgery.

Terraform import FAQ

Does terraform import create the configuration for me?

The import itself does not create configuration on either path. On Terraform 1.5+, adding -generate-config-out=FILE to terraform plan drafts resource blocks for imports that lack them, but the draft carries hard-coded IDs and null sensitive values, so it needs review before it is production code.

Can I import several resources in one operation?

With import blocks, yes: declare as many as you need and they land in one plan and apply, and Terraform 1.7+ supports for_each on the block. The CLI command handles exactly one resource per invocation.

What happens if the configuration does not match the resource?

Terraform treats the difference as a pending change. Depending on the attribute, the next apply either updates the object in place, sometimes with a restart, or destroys and recreates it, so read the plan symbols before applying.

How do I undo a terraform import?

If you have not applied an import block yet, delete the block. If the resource is in state, terraform state rm drops the binding while leaving the real object untouched, and 1.7+ offers the plannable removed block with destroy = false.

Can I import a resource into a module?

Yes. Use the full address, such as module.network.aws_vpc.main, in the import block’s to field or as the CLI address, and quote CLI addresses that contain bracket indexes.

Does terraform import work the same across providers?

The syntax is identical; the ID format is not, and each provider defines its own. For AWS, i-... and sg-... are native object IDs. A bucket uses its name as the identifier. Azure instead requires the full resource ID path starting /subscriptions/.... Google Cloud typically accepts project/region/name forms alongside the full path. Check the resource’s Registry page before importing.

Govern the imported estate

Importing gets an object into state, which answers what exists. It does not record the request and approval history or establish ownership. It also does not add lifecycle rules, including cost controls and decommissioning.

CloudBolt CMP records the request, the approval, and the owner alongside the resource, and it publishes a Terraform provider on the Terraform Registry — so it orchestrates the Terraform you already run rather than replacing it.

Where the managed boundary sits is an ownership question, not a syntax one. CloudBolt CMP tracks ownership across an imported estate and is free for up to 100 resources.

CloudBolt CMP is now free

All the capabilities. None of the cost.

Get CloudBolt CMP free

Explore the chapters:
AUTHOR
Joanne Chu

Senior Content Marketing Manager

Joanne Chu leads content and campaigns across cloud management, Kubernetes, and infrastructure optimization at CloudBolt. Her work explores the practical challenges IT and engineering teams face as they manage hybrid and multi-cloud environments. Before...
  Learn more

Related Blogs

 
thumbnail
Cloud Governance Guide: Framework, Models & Best Practices

Cloud governance decides how your organization uses the cloud. Who can create resources, where they can run, what they have…

 
thumbnail
Enterprise Cloud Management Best Practices

Most enterprises don’t run on one cloud. They run a hybrid cloud environment, with two or three public cloud service…

 
thumbnail
What it takes to cut Kubernetes GPU costs

Most teams running AI workloads on Kubernetes can see their total GPU spend, usually as one line item on the…