Terraform's data model assumes a one-to-one mapping between an HCL address and a real cloud object. When an organisation adopts Terraform on top of infrastructure that was created by another tool, by a console click, or by a script that pre-dates the codebase, the cloud objects already exist but Terraform has no record of them. Letting terraform apply re-create them would either collide on uniqueness constraints (an existing IAM role name, a DNS record, a globally unique bucket name) or quietly duplicate paid resources. The import path solves that exact problem: it links an existing real object to a Terraform address so the next plan treats the object as managed code rather than a stranger.
The Terraform Associate exam covers two documented mechanisms that carry the workflow forward. The legacy terraform import CLI command, available since the earliest releases of Terraform, performs an imperative one-shot import of a single resource into state. The newer import block, available from Terraform 1.5 onward, is declarative and appears in the plan output before any state change actually happens. Both call the provider's ImportResourceState method to read the real object's current attributes; both write a binding from an HCL address such as aws_instance.web to a cloud ID into the state file; and, critically, neither one writes the HCL configuration for the resource on its own unless explicitly combined with terraform plan -generate-config-out. The mental model the exam tests on every import question is that import populates state, not configuration; the operator is responsible for making the HCL match what import found.
Both paths share the same provider-side contract. A provider plugin must implement the Import operation for the specific resource type, and the documentation page for that resource type specifies the import identifier format. The format is provider-defined, not Terraform-defined: an AWS EC2 instance uses the bare instance ID i-0abcd1234efgh5678; an AWS IAM role uses the role name; an AWS Route 53 record uses a slash-separated composite ID Z1234567890ABC_example.com_A; a Google Cloud project IAM binding uses a slash-separated project/role pair. Reading the resource's documentation page before writing the address or the id argument is non-negotiable. A plan that fails with "Cannot import non-existent remote object" or "An item with the ID was not found" almost always traces back to an ID format that does not match the provider's parser, not to a missing object in the cloud.
The terraform import CLI
The imperative form takes two positional arguments: the destination resource address inside the current configuration, and the provider-specific identifier of the real object. The command updates state immediately and prints the imported attributes to stderr. It accepts a few notable flags: -input=false for non-interactive use in CI, -var and -var-file to supply variables that the provider configuration depends on, -state to point at an explicit local state file when the backend is local, and -lock / -lock-timeout to control state locking on backends that support it.
# Skeleton: write the empty resource block first, then import.
cat > main.tf <<'HCL'
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
resource "aws_instance" "web" {
# Body intentionally empty before import; will be filled in after.
}
HCL
terraform init
terraform import aws_instance.web i-0abcd1234efgh5678
After the command returns, the state file contains a fully populated aws_instance.web record but the HCL body is still empty. Running terraform plan immediately afterwards will show a long list of attribute changes, because Terraform compares an empty HCL body against the real-world attributes and proposes to "fix" everything by destroying or rewriting the resource. The operator must now copy the values surfaced by terraform state show aws_instance.web into the resource block, removing computed-only attributes (typically arn, id, timestamps, and any attribute marked Computed: true in the schema) and keeping the inputs that match reality. The iteration loop is: edit HCL, run terraform plan, observe the remaining diff, edit again, until terraform plan reports No changes.
# Verification loop after import.
terraform state show aws_instance.web > /tmp/imported.txt
$EDITOR main.tf # paste relevant attributes into the resource block
terraform plan # iterate until "No changes. Your infrastructure matches the configuration."
The CLI command accepts an address that points into a for_each or count instance of a resource, as long as the address is quoted to escape shell metacharacters. The form is module.networking.aws_subnet.private["us-east-1a"] for a keyed instance and module.networking.aws_subnet.private[0] for an indexed instance. The same address syntax works inside module trees of any depth.
# Importing into a for_each instance, single-quoted to protect [" "] from the shell.
terraform import 'module.networking.aws_subnet.private["us-east-1a"]' subnet-0123456789abcdef0
# Importing into a count instance.
terraform import 'module.networking.aws_subnet.public[0]' subnet-0fedcba9876543210
💡 Exam Trap:
terraform importonly ever updates state; it does not modify any HCL file on disk and it does not contact the provider to mutate the real object. Distractors that claim the CLI generates configuration, deletes the resource and re-creates it through Terraform, or overwrites the source file are wrong on every count. The single CLI invocation reads the real object once, writes the state binding, and stops.
The import block
The declarative form is an HCL block in any .tf file. It carries two required arguments, to (the destination resource address as an HCL expression, not a string) and id (the provider-specific identifier as a string or a string-returning expression), plus an optional provider argument to disambiguate when multiple provider instances exist. The block participates in the normal plan / apply lifecycle: the import is shown in terraform plan as a planned action with the + plus sign next to "will be imported", and it executes during terraform apply along with any other changes in the same run.
# In imports.tf, alongside the resource block in main.tf.
import {
to = aws_instance.web
id = "i-0abcd1234efgh5678"
}
resource "aws_instance" "web" {
ami = "ami-0abc123def456ghij"
instance_type = "t3.micro"
subnet_id = "subnet-0123456789abcdef0"
tags = {
Name = "web-tier"
}
}
A plan over the configuration above shows a single imported action and zero changes, because the resource block already reflects the real attributes. After a successful apply, the import block is typically removed from the codebase (the binding is permanent in state; the block is one-shot). Leaving the block in the repository is harmless but creates noise in future plans, where Terraform reports the import as already complete.
The to argument supports the full resource address grammar, including module paths, count indices, and for_each keys. The address is an HCL reference and is therefore not quoted; the id argument is always a string.
# Multi-instance import using for_each on the import block.
locals {
existing_buckets = {
logs = "acme-app-logs-2018"
assets = "acme-app-assets-2018"
backup = "acme-app-backup-2019"
}
}
import {
for_each = local.existing_buckets
to = aws_s3_bucket.legacy[each.key]
id = each.value
}
resource "aws_s3_bucket" "legacy" {
for_each = local.existing_buckets
bucket = each.value
}
The for_each meta-argument on the import block expands into one import per element, addressed by the matching for_each key on the destination resource. The keys on the import and the keys on the resource must line up; if a key exists on one side but not the other, the plan reports either an orphaned import or a missing import target.
💡 Exam Trap: The
importblock is the only Terraform construct that ties an existing real object into state through aplan-then-applycycle. The CLI form (terraform import) is single-shot, single-run, and not visible in a plan; the block form is declarative, plan-visible, codifiable in version control, and supportsfor_eachfor bulk operations. Exam stems that emphasise reviewability, code review, GitOps, or pipeline integration are pointing at the block, not the CLI.
Generating configuration with -generate-config-out
The pair of features that makes import blocks substantially less painful than the CLI is terraform plan -generate-config-out=<path>. When this flag is set on a plan, Terraform reads the attributes returned by the provider for every resource referenced in an import block whose destination address has no resource block in configuration, and writes a draft HCL file for those resources at the given path. The output file is a starting point: it contains every settable attribute the provider exposes, with computed-only attributes commented out and inter-resource references left as literal strings.
# Start with import blocks and no resource bodies, then ask Terraform to draft the HCL.
cat > imports.tf <<'HCL'
import {
to = aws_iam_role.legacy_lambda
id = "legacy-lambda-exec"
}
import {
to = aws_iam_role_policy_attachment.legacy_lambda_logs
id = "legacy-lambda-exec/arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}
HCL
terraform plan -generate-config-out=generated.tf
After the command returns, generated.tf holds draft resource blocks for both addresses, with attribute values pulled from the live cloud objects. The operator then edits generated.tf by hand to introduce variables, cross-resource references, locals, and any organisation-specific conventions, and finally renames or moves the file into the regular configuration layout. The -generate-config-out flag refuses to overwrite an existing file, so the second invocation in the same iteration loop typically targets a different path or follows a delete.
📊 Limit:
terraform plan -generate-config-outwrites draft configuration only for resources that already have animportblock targeting them and that do not already have aresourceblock in configuration. It is not a bulk reverse-engineering tool: there is no flag that asks Terraform to walk a cloud account and emit HCL for every object it finds. Operators who need full account reverse-engineering reach for separate tools such asterraformer(community) or vendor-specific exporters, then refine the output by hand.
Removed block and moved block: complementary maintenance operations
The exam treats import as one corner of a maintenance triangle that includes two related declarative blocks. The moved block, available from Terraform 1.1 onward, records that a resource has been renamed inside the configuration so Terraform updates the state binding rather than destroying the old address and creating a new one. The removed block, available from Terraform 1.7 onward, records that a resource is being removed from configuration but its real-world object should be left intact: Terraform removes the state binding instead of running the provider's Delete operation.
# Renaming a resource from old name to new name without destroying it.
moved {
from = aws_iam_role.lambda
to = aws_iam_role.lambda_exec
}
resource "aws_iam_role" "lambda_exec" {
name = "lambda-exec"
assume_role_policy = data.aws_iam_policy_document.assume_lambda.json
}
# Removing the binding from state without destroying the real object,
# because another stack now manages it.
removed {
from = aws_iam_role.legacy_lambda
lifecycle {
destroy = false
}
}
moved, import, and removed together cover the three state-binding edits that arise during refactors and reorganisations: rename in place (moved), bring an unmanaged object under management (import), and let go of an object without destroying it (removed with destroy = false). Treating them as a family on the exam clears up many of the trickier "which block does X" questions.
⚠️ Anti-Pattern: Reaching for
terraform state rmfollowed byterraform importto "rename" a resource. The pair has the same end state as a singlemovedblock, but it bypasses the plan, leaves no record in version control, runs without state locking review, and is invisible in code review. Refactor in declarative blocks; reserveterraform state rmfor the genuine cases where a binding must disappear with no replacement and there is no plan to keep the object.
Decision Anchor: which import path to use
Choose terraform import (CLI) when the workspace is operating against a local backend, the operator is iterating in a scratch directory, and the import is a one-off interactive task with no need for version-control review. The command is fast, requires no import block in the codebase, and runs outside the normal plan loop. Choose the import block when the workspace is collaborative, when the import should be reviewed in a pull request before it lands in state, when several resources must be imported together as part of a single apply, or when for_each over a map of existing IDs is the natural way to express the bulk operation. The block form is also the only path that pairs with terraform plan -generate-config-out for drafting HCL.
🎯 Scenario: A platform team inherits an account with 38 S3 buckets created in the console over several years. The team writes a single
importblock withfor_eachover alocals.existing_bucketsmap of bucket names, runsterraform plan -generate-config-out=buckets.tfto draft 38 resource bodies, opens a pull request that contains theimportblock plus the generated bodies, and waits for two reviewers to approve. On merge, the CI pipeline runsterraform applyand the entire fleet enters state in one run. None of this is possible with the CLI form: it would require 38 manual invocations, 38 separate commits to the generated HCL, and no plan review before each binding lands.
Limits the exam tests
The id format is provider-defined and resource-defined: every resource type's documentation page in the provider documentation has a section called "Import" that lists the exact string format the provider accepts. The exam writes plausible-looking but wrong IDs into distractors (a UUID where the provider expects a name, or a slash-separated composite where the provider expects a bare ID); reading the provider's import section is the only defence. The import operation reads the real object once at the moment of import; it does not perpetually re-discover the object on subsequent runs. If the cloud object disappears outside Terraform after the import, the next plan reports drift the same way it would for any resource. Imports do not support arbitrary provider-side filtering: the operator must already know the cloud ID. There is no Terraform-native "discover all S3 buckets" command; that is the operator's job, typically through the cloud provider's CLI (aws s3api list-buckets, gcloud storage buckets list) before the import block is written.
💡 Exam Trap: The phrase "Terraform writes the HCL configuration during import" is wrong for both the CLI and the block, with one specific exception:
terraform plan -generate-config-out=<file>writes a draft file at the given path, but only for resources that have animportblock and no existingresourceblock. The bare CLI never writes HCL; the bareimportblock never writes HCL; only the explicit-generate-config-outflag does.
