In 05-01 we described the worst possible outcome of an apply: the process dies between the API call and the state being written. The resource exists in the cloud, Terraform does not know about it, the next apply tries to create it again and fails with "already exists". We said the solution was to import and left it for this module. In 03-02 the same thing happened with a resource removed from the state by a state rm, and the conclusion was identical.
But the interrupted case is the least frequent one. Importing is mostly used for something more everyday and more uncomfortable: adopting infrastructure that existed before your code. Almost no real platform is born with Terraform. It is born in the web console, it grows through a succession of emergencies, and one day somebody decides that from now on everything will be infrastructure as code. That day begins a job that can last months and that this lesson describes in full.
EcoMarket has two open cases that have been waiting a while:
- The invoices bucket. Somebody in administration created it through the console in 2024 to archive tax invoices. It holds seven years of documents with a legal retention obligation, it has a lifecycle policy set up by hand and nobody dares touch it. It is not in Terraform and it cannot be destroyed or recreated.
- The small-hours load balancer. During an incident, somebody created an extra load balancer from the console to divert traffic. It worked, the incident was closed, and the load balancer is still there, outside the state, costing money, with nobody remembering exactly how it is configured.
By the end of the lesson, both will be inside the state, with their configuration written, reviewed and giving a zero-change plan.
- Why you have to import
Four situations, with very different frequencies.
| Situation | Frequency | Urgency | Typical volume |
|---|---|---|---|
| Infrastructure predating Terraform | Very high | Low: it is a project | Dozens or hundreds of resources |
| A resource created by hand during an emergency | High | Medium: the sooner, the less drift | 1-5 resources |
A resource lost from the state (state rm, interrupted apply, corrupt state) |
Medium | High: the apply is broken |
1-3 resources |
| Migration from another tool (CloudFormation, ARM templates, Deployment Manager, Pulumi) | Low | Low | Everything at once |
The second case deserves a note, because it generates the most debate in teams. When there is an incident at three in the morning, creating the resource by hand is the right thing to do: the priority is restoring the service, not keeping the workflow pure. What is not right is failing to import it afterwards. A healthy platform has an explicit rule: anything created by hand during an incident is imported before the incident is closed, and that is written into the post-incident report as a task with an owner and a date.
Without that rule, drift accumulates and the day comes when nobody knows what is deployed. The symptom is familiar: somebody runs terraform destroy on an environment they believe is empty and discovers that half the things are still there, because they were never in the state.
- What an import actually does
This has to be crystal clear before you type a single command, because half the problems come from a mistaken expectation.
flowchart LR
subgraph before["BEFORE importing"]
N1["CLOUD<br/>The bucket exists"]
E1["STATE<br/>empty"]
C1["CONFIGURATION<br/>??"]
end
subgraph after["AFTER importing"]
N2["CLOUD<br/>The bucket exists<br/><i>unchanged</i>"]
E2["STATE<br/>aws_s3_bucket.invoices<br/>with ALL its real attributes"]
C2["CONFIGURATION<br/>whatever YOU wrote"]
end
before ==>|"terraform import"| after
What it does:
- Reads the real resource by calling the provider's API.
- Writes all its current attributes into the state, under the address you give it.
- Nothing else.
What it does NOT do:
| Does not do | Consequence |
|---|---|
It does not write configuration (except with -generate-config-out) |
You must write the .tf that describes the resource |
| It does not modify the resource in the cloud | Importing is read-only as far as the infrastructure is concerned |
| It does not validate that your configuration matches | That is what the subsequent plan tells you |
| It does not import dependent resources | Importing a bucket does not import its policy, its versioning or its encryption |
| It does not recover attributes the API does not return | Passwords, keys and some fields come back empty |
The consequence of the first two rows is the axis of the whole flow: importing makes the state tell the truth; writing the configuration is your job, and the plan is the exam.
If your configuration describes something different from what is in the cloud, the subsequent plan will propose changing it — or, in the worst case, destroying and recreating it. That plan is exactly the one to read with a magnifying glass.
- The
terraform import command: the classic flow
terraform import command: the classic flowADDRESS: the resource's address in your configuration:aws_s3_bucket.invoices,module.data.aws_db_instance.main,aws_subnet.private["eu-west-1a"].ID: the resource's identifier in the provider. Its format depends on the resource type and it is the biggest stumbling block (section 4).
Options that actually get used:
| Option | What for |
|---|---|
-var-file=file.tfvars |
The same as in plan: the configuration needs its variables |
-var 'key=value' |
Individual variables |
-provider=... |
Deprecated: use provider in the import block or an alias configuration |
-input=false |
In automation, so that it does not prompt |
-lock-timeout=60s |
Import writes to the state, so it takes the lock |
The complete flow with the invoices bucket
Step 0: find out what has to be imported. You do not import blind.
$ aws s3api get-bucket-location --bucket ecomarket-facturas-archivo
{
"LocationConstraint": "eu-west-1"
}
$ aws s3api get-bucket-versioning --bucket ecomarket-facturas-archivo
{
"Status": "Enabled"
}
$ aws s3api get-bucket-encryption --bucket ecomarket-facturas-archivo
{
"ServerSideEncryptionConfiguration": {
"Rules": [
{
"ApplyServerSideEncryptionByDefault": {"SSEAlgorithm": "AES256"},
"BucketKeyEnabled": true
}
]
}
}
$ aws s3api get-bucket-tagging --bucket ecomarket-facturas-archivo
{
"TagSet": [
{"Key": "Departamento", "Value": "Administracion"},
{"Key": "Retencion", "Value": "7-anios"}
]
}
$ aws s3api get-bucket-lifecycle-configuration --bucket ecomarket-facturas-archivo
{
"Rules": [
{
"ID": "archivar-antiguas",
"Status": "Enabled",
"Filter": {"Prefix": ""},
"Transitions": [
{"Days": 90, "StorageClass": "GLACIER"}
]
}
]
}Five calls, five pieces of information. And one critical observation: in the modern AWS provider, an S3 bucket is not one resource but six:
aws_s3_bucketaws_s3_bucket_versioningaws_s3_bucket_server_side_encryption_configurationaws_s3_bucket_lifecycle_configurationaws_s3_bucket_public_access_blockaws_s3_bucket_policy
All six have to be imported, one by one. It is the clearest example of the fact that importing a resource is rarely importing one resource.
Step 1: write the configuration. The block has to exist before the import, even if it is minimal:
# infra/app/invoices.tf
resource "aws_s3_bucket" "invoices" {
bucket = "ecomarket-facturas-archivo"
}If it does not exist, the error is unmistakable:
╷ │ Error: resource address "aws_s3_bucket.invoices" does not exist in the configuration. │ │ Before importing this resource, please create its configuration in the root module. ╵
Step 2: import.
$ terraform import -var-file=prod.tfvars aws_s3_bucket.invoices ecomarket-facturas-archivo
aws_s3_bucket.invoices: Importing from ID "ecomarket-facturas-archivo"...
aws_s3_bucket.invoices: Import prepared!
Prepared aws_s3_bucket for import
aws_s3_bucket.invoices: Refreshing state... [id=ecomarket-facturas-archivo]
Import successful!
The resources that were imported are shown above. These resources are now in
your Terraform state and will henceforth be managed by Terraform.Step 3: look at what was imported.
$ terraform state show aws_s3_bucket.invoices
# aws_s3_bucket.invoices:
resource "aws_s3_bucket" "invoices" {
arn = "arn:aws:s3:::ecomarket-facturas-archivo"
bucket = "ecomarket-facturas-archivo"
bucket_domain_name = "ecomarket-facturas-archivo.s3.amazonaws.com"
bucket_regional_domain_name = "ecomarket-facturas-archivo.s3.eu-west-1.amazonaws.com"
force_destroy = false
hosted_zone_id = "Z1BKCTXD74EZPE"
id = "ecomarket-facturas-archivo"
object_lock_enabled = false
region = "eu-west-1"
request_payer = "BucketOwner"
tags = {
"Departamento" = "Administracion"
"Retencion" = "7-anios"
}
tags_all = {
"Departamento" = "Administracion"
"Retencion" = "7-anios"
}
}Step 4: the plan, which is the exam.
$ terraform plan -var-file=prod.tfvars
Terraform will perform the following actions:
# aws_s3_bucket.invoices will be updated in-place
~ resource "aws_s3_bucket" "invoices" {
id = "ecomarket-facturas-archivo"
~ tags = {
- "Departamento" = "Administracion" -> null
- "Retencion" = "7-anios" -> null
}
~ tags_all = {
- "Departamento" = "Administracion" -> null
- "Retencion" = "7-anios" -> null
}
}
Plan: 0 to add, 1 to change, 0 to destroy.The plan is not clean. Terraform wants to delete the tags, because the configuration from step 1 does not declare them. If you applied now, you would lose information the administration team uses for its reports. This is exactly the moment to stop and adjust.
Step 5: adjust the configuration until the plan is clean.
resource "aws_s3_bucket" "invoices" {
bucket = "ecomarket-facturas-archivo"
tags = {
Departamento = "Administracion"
Retencion = "7-anios"
}
lifecycle {
# Seven years of invoices with a legal retention obligation.
# This is the first thing you write, not the last.
prevent_destroy = true
}
}Step 6: repeat for the five satellite resources.
terraform import -var-file=prod.tfvars \
aws_s3_bucket_versioning.invoices ecomarket-facturas-archivo
terraform import -var-file=prod.tfvars \
aws_s3_bucket_server_side_encryption_configuration.invoices ecomarket-facturas-archivo
terraform import -var-file=prod.tfvars \
aws_s3_bucket_lifecycle_configuration.invoices ecomarket-facturas-archivo
terraform import -var-file=prod.tfvars \
aws_s3_bucket_public_access_block.invoices ecomarket-facturas-archivoEach one with its configuration block written beforehand, and each one with its plan afterwards.
The cycle, summarised
flowchart TD
A["Inspect the real resource<br/>with the provider's CLI"] --> B["Write the minimal (or complete)<br/>configuration"]
B --> C["terraform import ADDRESS ID"]
C --> D["terraform state show<br/>see what went in"]
D --> E["terraform plan"]
E --> F{"Zero-change plan?"}
F -->|"No: in-place changes"| G["Adjust the configuration<br/>with the real values"]
G --> E
F -->|"No: forces replacement"| H["⚠️ STOP<br/>An immutable attribute does not match"]
H --> G
F -->|"Yes"| I["Confirm against the console<br/>and commit"]
The forces replacement branch deserves its own warning, and that is section 13.
What you need to know about the command
| Characteristic | Detail |
|---|---|
| It writes directly to the state | There is no prior plan, no apply. It is immediate and irreversible without a backup |
| It takes the state lock | Like any write operation (03-04) |
| One resource per invocation | A hundred resources are a hundred commands |
| It leaves no trace in the repository | Nobody can review in a pull request that you imported the right thing |
| It is not reproducible | If somebody recreates the environment, they have to remember the commands |
The last three rows are the whole reason the import block exists.
- Import identifiers
The identifier is not always the resource's id and its format changes by resource type. It is the number-one source of frustration when importing.
Where to look it up: at the bottom of each resource's documentation page, in the "Import" section. Always. There is no shortcut and no general pattern that holds.
AWS
| Resource | ID format | Example |
|---|---|---|
aws_s3_bucket |
Bucket name | ecomarket-facturas-archivo |
aws_instance |
Instance ID | i-0a1b2c3d4e5f67890 |
aws_vpc |
VPC ID | vpc-0a1b2c3d4e5f67890 |
aws_subnet |
Subnet ID | subnet-0a1b2c3d4e5f67890 |
aws_security_group |
Group ID | sg-0a1b2c3d4e5f67890 |
aws_vpc_security_group_ingress_rule |
The rule's ID (not the group's) | sgr-0a1b2c3d4e5f67890 |
aws_db_instance |
Identifier, not the ARN or the ID | ecomarket-prod-db |
aws_lb |
Full ARN | arn:aws:elasticloadbalancing:eu-west-1:123456789012:loadbalancer/app/ecomarket-lb/abc123 |
aws_lb_target_group |
Full ARN | arn:aws:elasticloadbalancing:...:targetgroup/ecomarket-tg/def456 |
aws_lb_listener |
The listener's full ARN | arn:aws:elasticloadbalancing:...:listener/app/.../abc/def |
aws_iam_role |
Role name | ecomarket-prod-web |
aws_iam_role_policy |
role:policy_name |
ecomarket-prod-web:bucket-access |
aws_iam_role_policy_attachment |
role/policy_arn |
ecomarket-prod-web/arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore |
aws_iam_instance_profile |
Profile name | ecomarket-prod-web |
aws_autoscaling_group |
Group name | ecomarket-prod-web-asg |
aws_launch_template |
Template ID | lt-0a1b2c3d4e5f67890 |
aws_route_table_association |
subnet_id/route_table_id |
subnet-0a1b.../rtb-0c2d... |
aws_secretsmanager_secret |
The secret's ARN | arn:aws:secretsmanager:eu-west-1:123456789012:secret:ecomarket/prod/db-AbC123 |
aws_cloudwatch_log_group |
Group name | /ecomarket/prod/app |
Notice the inconsistencies, because they are real and there is no logic that unifies them: the bucket goes by name, the instance by ID, the database by identifier, the load balancer by full ARN, and the route table association by two identifiers joined with a /.
Azure
Azure is the most uniform of the three: always the complete resource ID.
| Resource | Format |
|---|---|
| Any Azure resource | /subscriptions/<sub>/resourceGroups/<rg>/providers/<provider>/<type>/<name> |
/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/ecomarket-prod-rg/providers/Microsoft.Network/virtualNetworks/ecomarket-prod-vnet
Getting hold of it is straightforward:
$ az network vnet show -g ecomarket-prod-rg -n ecomarket-prod-vnet --query id -o tsv
/subscriptions/0000.../resourceGroups/ecomarket-prod-rg/providers/Microsoft.Network/virtualNetworks/ecomarket-prod-vnet
# All the IDs in a resource group, in one go
$ az resource list -g ecomarket-prod-rg --query '[].{type:type, id:id}' -o tableThe uniformity has a downside: the IDs are enormous, some segments are case-sensitive (resourceGroups, not resourcegroups) and a one-letter mistake produces an unhelpful 404.
GCP
Somewhere in between: generally project/location/name, with variations.
| Resource | Format | Example |
|---|---|---|
google_compute_network |
project/name |
ecomarket-prod/ecomarket-vpc |
google_compute_subnetwork |
project/region/name |
ecomarket-prod/europe-west1/ecomarket-subnet |
google_compute_instance |
project/zone/name |
ecomarket-prod/europe-west1-b/web-01 |
google_storage_bucket |
project/name or just the name |
ecomarket-prod/ecomarket-images |
google_sql_database_instance |
project/name |
ecomarket-prod/ecomarket-pg |
google_project_iam_member |
project role member (spaces) |
"ecomarket-prod roles/storage.admin serviceAccount:web@..." |
google_secret_manager_secret |
projects/<num>/secrets/<id> |
projects/123456/secrets/ecomarket-db |
The google_project_iam_member case is especially awkward because the separators are spaces, which forces you to quote in the shell.
How to work it out when the documentation is not enough
# 1. The "Import" section of the resource's documentation. ALWAYS first.
# 2. If you already manage an equivalent resource, look at its id in the state:
$ terraform state show aws_lb.main | grep -E '^\s+(id|arn)'
arn = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:loadbalancer/app/ecomarket-prod-lb/abc123"
id = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:loadbalancer/app/ecomarket-prod-lb/abc123"
# 3. The state's "id" attribute is, in the vast majority of cases, the
# import identifier for that resource type. It is the best trick
# of them all.
# 4. Try it with an import block and -generate-config-out, which fails
# without writing anything to the state if the ID is wrong.Point 3 is worth underlining: if you already manage a resource of the same type, its id in the state tells you the exact format. It is more reliable than interpreting the documentation.
- Terraform 1.5's
import block
import blockSince version 1.5 there is a declarative form, and it should be your default choice.
import {
to = aws_s3_bucket.invoices
id = "ecomarket-facturas-archivo"
}
resource "aws_s3_bucket" "invoices" {
bucket = "ecomarket-facturas-archivo"
tags = {
Departamento = "Administracion"
Retencion = "7-anios"
}
lifecycle {
prevent_destroy = true
}
}Two arguments:
to: the resource's address in the configuration.id: the identifier in the provider, the same one the command would use.
And two optional ones:
provider: when the resource lives in a provider configuration with analias(another region, another account).identity(Terraform 1.12+): in providers that support it, this replacesidwith an object holding the fields that identify the resource, which avoids the concatenated, ambiguous strings from section 4.
Why it is better
| Criterion | The terraform import command |
The import block |
|---|---|---|
| You see the effect before applying it | No: it writes the state immediately | Yes: it appears in the plan |
| Reviewable in a pull request | No: it is a command somebody ran | Yes: it is code |
| Runnable from the pipeline | Requires a manual step outside the flow | Yes: an ordinary apply |
| Several resources at once | One command per resource | Yes: several blocks, or for_each |
| Generates configuration | No | Yes, with -generate-config-out |
| Reproducible | No | Yes, as long as the block is in the code |
| Reversible if something goes wrong | state rm after the fact |
Delete the block before the apply |
| Available since | Always | 1.5 |
The first row is the decisive one. With the block, the plan shows what is going to happen:
$ terraform plan -var-file=prod.tfvars
aws_s3_bucket.invoices: Preparing import... [id=ecomarket-facturas-archivo]
aws_s3_bucket.invoices: Refreshing state... [id=ecomarket-facturas-archivo]
Terraform will perform the following actions:
# aws_s3_bucket.invoices will be imported
resource "aws_s3_bucket" "invoices" {
arn = "arn:aws:s3:::ecomarket-facturas-archivo"
bucket = "ecomarket-facturas-archivo"
id = "ecomarket-facturas-archivo"
object_lock_enabled = false
region = "eu-west-1"
tags = {
"Departamento" = "Administracion"
"Retencion" = "7-anios"
}
}
Plan: 1 to import, 0 to add, 0 to change, 0 to destroy.1 to import, 0 to add, 0 to change, 0 to destroy is the ideal result: it is imported and nothing is touched. If instead you see 1 to import, 0 to add, 1 to change, your configuration differs from the real resource and has to be adjusted before applying. And if a must be replaced shows up, it is an emergency: section 13.
And now the difference that really matters compared with the command: if you do not like the plan, you delete the block and nothing has happened. With the command, the state would already have been written.
Importing several resources at once
# The bucket and its five satellites, in a single reviewable plan.
import {
to = aws_s3_bucket.invoices
id = "ecomarket-facturas-archivo"
}
import {
to = aws_s3_bucket_versioning.invoices
id = "ecomarket-facturas-archivo"
}
import {
to = aws_s3_bucket_server_side_encryption_configuration.invoices
id = "ecomarket-facturas-archivo"
}
import {
to = aws_s3_bucket_lifecycle_configuration.invoices
id = "ecomarket-facturas-archivo"
}
import {
to = aws_s3_bucket_public_access_block.invoices
id = "ecomarket-facturas-archivo"
}Importing with for_each
Since Terraform 1.7, import blocks accept for_each, which lets you import a whole set of resources with a single block. EcoMarket's case: adopting the subnets that existed before Terraform.
locals {
# Map of pre-existing subnets: zone -> real ID in AWS.
# Obtained with: aws ec2 describe-subnets --filters ...
subnets_to_import = {
"eu-west-1a" = "subnet-0a1b2c3d4e5f67890"
"eu-west-1b" = "subnet-0b2c3d4e5f6789a1"
"eu-west-1c" = "subnet-0c3d4e5f6789a1b2"
}
}
import {
for_each = local.subnets_to_import
# each.key is the key of the TARGET resource's for_each.
to = aws_subnet.private[each.key]
id = each.value
}
resource "aws_subnet" "private" {
for_each = local.private_subnets
vpc_id = aws_vpc.main.id
availability_zone = each.key
cidr_block = each.value.cidr
tags = merge(local.common_tags, {
Name = "${local.prefix}-priv-${each.key}"
})
}The import block's for_each and the resource's are independent, but the keys have to correspond. If the import map has a zone the resource does not generate, the error is clear:
╷ │ Error: Configuration for import target does not exist │ │ The configuration for the given import "aws_subnet.private[\"eu-west-1d\"]" │ does not exist. All target instances must have an associated resource │ configuration. ╵
When to delete the import blocks
An import block whose resource is already in the state does nothing: Terraform ignores it silently. So technically they could stay forever.
In practice, they get deleted, and there are three reasons:
- Noise: after a year, twenty
importblocks from old adoptions make the code harder to read. - A latent hazard: if somebody does a
state rmon that resource, the block comes back to life and reimports, perhaps with an ID that no longer refers to the same object. - Misleading reproducibility: the blocks suggest the configuration can be applied from scratch, and that is not true: in a new account those IDs do not exist and the
applyfails.
The recommended flow, in two pull requests:
| Pull request | Content | Expected result |
|---|---|---|
| 1 | import blocks + the resources' configuration |
N to import, 0 to change, 0 to destroy |
| 2 | Removal of the import blocks |
No changes |
If the second pull request shows any change at all, something went wrong in the first.
- Automatic configuration generation
Terraform 1.6 added -generate-config-out, which writes the configuration for you from the real resource.
# 1. Only the import block, WITHOUT the resource block
$ cat import.tf
import {
to = aws_lb.small_hours
id = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:loadbalancer/app/incidente-2026-03/9f8e7d6c5b4a3210"
}
# 2. Generate
$ terraform plan -var-file=prod.tfvars -generate-config-out=generated.tf
Terraform will perform the following actions:
# aws_lb.small_hours will be imported
# (config will be generated)
resource "aws_lb" "small_hours" {
...
}
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.
╵
Terraform has generated configuration and written it to generated.tf. Please
review the configuration and edit it as necessary before adding it to version
control.The generated file:
# __generated__ by Terraform
# Please review these resources and move them into your main configuration files.
# __generated__ by Terraform from "arn:aws:elasticloadbalancing:..."
resource "aws_lb" "small_hours" {
desync_mitigation_mode = "defensive"
drop_invalid_header_fields = false
enable_cross_zone_load_balancing = true
enable_deletion_protection = false
enable_http2 = true
enable_tls_version_and_cipher_suite_headers = false
enable_waf_fail_open = false
enable_xff_client_port = false
idle_timeout = 60
internal = false
ip_address_type = "ipv4"
load_balancer_type = "application"
name = "incidente-2026-03"
preserve_host_header = false
security_groups = ["sg-0d4e5f6789a1b2c3"]
tags = {}
tags_all = {}
xff_header_processing_mode = "append"
access_logs {
bucket = ""
enabled = false
prefix = ""
}
subnet_mapping {
subnet_id = "subnet-0a1b2c3d4e5f67890"
}
subnet_mapping {
subnet_id = "subnet-0b2c3d4e5f6789a1"
}
}What has to be cleaned up
The generated configuration works but it is not code you would want to maintain. What needs fixing, in order of importance:
| Problem | Example from the generated file | What to do |
|---|---|---|
| Literal references | security_groups = ["sg-0d4e..."] |
Replace with [aws_security_group.load_balancer.id] |
| Every default value written out | enable_http2 = true, idle_timeout = 60 |
Delete the ones that add nothing; they make the code unreadable |
| Empty or disabled blocks | access_logs { bucket = "" enabled = false } |
Delete the whole block |
| Repeated blocks instead of dynamic ones | Two hand-written subnet_mapping blocks |
Convert to subnets = [...] or dynamic |
| No project tags | tags = {} |
Add merge(local.common_tags, ...) |
No lifecycle |
There is none | Add prevent_destroy where it belongs |
| Read-only attributes | Sometimes arn or id slips through |
Delete them: the apply would fail |
| Automatic resource names | aws_lb.small_hours |
Rename per the team's convention, before importing |
The clean version, integrated into EcoMarket's code:
resource "aws_lb" "secondary" {
name = "incidente-2026-03"
load_balancer_type = "application"
internal = false
security_groups = [aws_security_group.load_balancer.id]
subnets = [for z, s in module.network.public_subnets : s.id]
enable_deletion_protection = true # ← a deliberate change, it was not there
enable_cross_zone_load_balancing = true
tags = merge(local.common_tags, {
Name = "${local.prefix}-lb-secondary"
Origin = "imported-incidente-2026-03"
})
}From thirty generated lines to twelve written ones. And notice enable_deletion_protection = true: it is a deliberate change to what was there, so the plan will no longer come out clean. That is fine, as long as it is conscious and split into its own pull request.
Limitations
| Limitation | Detail |
|---|---|
| It is still experimental | The format may change between versions |
Only with import blocks |
It does not work with the command |
| It does not generate dependent resources | It generates aws_s3_bucket, not its five satellites |
| It does not infer references | Everything stays literal; you write the dependency graph yourself |
| No use if the resource is already in the state | It is only for new imports |
It fails if a resource block already exists at that address |
By design: it does not overwrite your code |
| Some providers support it poorly | Missing attributes or values the apply rejects |
Use it as a starting point, never as the final result. Its real value is that it tells you which attributes the resource has, which is exactly what you do not know when importing something somebody else created two years ago.
- Importing inside modules, with
for_each and with count
for_each and with countThe target address is the resource's full address, with all its prefixes and indices.
Inside a module
With nested modules, you chain them:
import {
to = module.platform.module.data.aws_s3_bucket.images
id = "ecomarket-prod-images-noble-bass"
}With the command, you have to quote it because the shell interprets characters:
With for_each
With the command, the escaping is what causes the most trouble:
# bash/zsh: single quotes outside, double quotes inside
terraform import 'aws_subnet.private["eu-west-1a"]' subnet-0a1b2c3d4e5f67890
# Inside a module, with for_each
terraform import 'module.network.aws_subnet.private["eu-west-1a"]' subnet-0a1b2c3d4e5f67890
# ❌ Without quotes: the shell eats the brackets and the quotes
terraform import aws_subnet.private["eu-west-1a"] subnet-0a1b...
# Error: Index value required
# PowerShell: the double quotes have to be escaped
terraform import 'aws_subnet.private[\"eu-west-1a\"]' subnet-0a1b...This is the best practical argument for the import block: there is no shell escaping at all, because it is HCL.
With count
And a warning here: importing to a count index is fragile for the same reason count is fragile. If the number of instances changes tomorrow, the indices shift. If you are importing into a resource with count, first consider whether it should have for_each instead (02-03).
With aliased providers
provider "aws" {
alias = "paris"
region = "eu-west-3"
}
import {
to = aws_s3_bucket.paris_replica
id = "ecomarket-facturas-replica-paris"
provider = aws.paris # ← without this it would look in eu-west-1 and fail
}Forgetting the provider produces a baffling "resource not found" error, because the resource exists perfectly well... in another region.
- Combining
import and moved
import and movedA frequent case during adoption: you import a resource and then realise its proper home is inside a module, or under a different name. Combining import and moved (03-05) solves it without touching the infrastructure.
The recommended sequence, in two steps.
Step 1: import wherever it is simplest, normally the root:
import {
to = aws_s3_bucket.invoices
id = "ecomarket-facturas-archivo"
}
resource "aws_s3_bucket" "invoices" {
bucket = "ecomarket-facturas-archivo"
tags = { Departamento = "Administracion", Retencion = "7-anios" }
}Apply and confirm a zero-change plan.
Step 2: move it into the module, in another pull request:
# The resource is removed from the root and added to the "archive" module.
moved {
from = aws_s3_bucket.invoices
to = module.archive.aws_s3_bucket.invoices
}
module "archive" {
source = "./modules/archive"
bucket_name = "ecomarket-facturas-archivo"
tags = { Departamento = "Administracion", Retencion = "7-anios" }
}Plan: 0 to add, 0 to change, 0 to destroy. Terraform will perform the following actions: # aws_s3_bucket.invoices has moved to module.archive.aws_s3_bucket.invoices
Why two steps rather than importing straight to the final address? You can import straight to module.archive.aws_s3_bucket.invoices, and if you have the module written and tested, do that. The two steps make sense when the module does not exist yet or when its interface is still being decided: first you secure the resource in the state, then you decide where it lives. Separating "stop losing the resource" from "organise the code" reduces the risk of each pull request.
What you must never do: mix an import and a moved on the same resource in the same pull request. The resulting plan is hard to read and a mistake is caught late.
- What is not imported and how to spot it
Resources with no import support
Not every resource type is importable. The usual suspects:
| Category | Examples | Why |
|---|---|---|
| Ephemeral or action resources | null_resource, terraform_data, time_sleep |
They represent nothing in any API |
Resources from the random provider |
random_pet, random_password, random_id |
Their value does not exist outside the state |
Resources from the tls provider |
tls_private_key |
The private key only ever lived in the state |
| Some relationship resources | Certain older *_association and *_attachment |
The provider never implemented Importer |
The error is unmistakable:
For the random provider there is a documented trick: terraform import random_pet.suffix noble-bass works on some resources because their id is the value. But if what you lost is a random_password, the password cannot be recovered from anywhere: it has to be rotated.
Attributes the API does not return
This is the silent problem and the most dangerous one, because it produces no error.
| Attribute | Resource | What happens on import |
|---|---|---|
password |
aws_db_instance |
It ends up empty in the state |
user_data |
aws_instance |
Sometimes it arrives, sometimes only its hash |
secret_string |
aws_secretsmanager_secret_version |
The value is not imported |
private_key |
tls_private_key |
Unrecoverable |
admin_password |
azurerm_linux_virtual_machine |
Empty |
| Access keys | aws_iam_access_key |
The secret is only shown at creation time |
The symptom shows up in the first plan afterwards:
# aws_db_instance.invoices will be updated in-place
~ resource "aws_db_instance" "invoices" {
+ password = (sensitive value)
}Terraform wants to write the password because there is none in the state. If your var.db_password is the correct one, applying is harmless (it sets it back to the same value). If it is not, you change the production password and the application stops connecting.
How to catch it before applying:
# Which attributes ended up empty or null after the import?
$ terraform state show aws_db_instance.invoices | grep -E '= (null|"")'
password = null
final_snapshot_identifier = nullAnd how to deal with it:
resource "aws_db_instance" "invoices" {
# ...
password = var.invoices_db_password # must be the REAL one, verified beforehand
lifecycle {
# Alternative if you cannot know the real password: ignore it.
# Terraform stops managing it, and rotation happens some other way.
ignore_changes = [password]
}
}The checklist
# 1. Does the resource support import? The "Import" section of its documentation.
# 2. Which attributes ended up empty?
terraform state show <address> | grep -E '= (null|""|\[\])'
# 3. Does the plan want to write any sensitive attribute?
terraform plan | grep -A2 'sensitive value'
# 4. Are there satellite resources still to import?
# Compare the console with what is in the state.
- Verification afterwards: the zero-change plan and its traps
Verification at three levels
Level 1: the zero-change plan.
$ terraform plan -var-file=prod.tfvars -detailed-exitcode
No changes. Your infrastructure matches the configuration.
$ echo $?
0It is necessary, but not sufficient. A zero-change plan means the configuration matches what is in the state and in the cloud for the attributes Terraform manages. It says nothing about the satellite resources you have not even declared.
Level 2: compare against the console.
# What Terraform believes
$ terraform state show aws_s3_bucket.invoices
# What is really there
$ aws s3api get-bucket-versioning --bucket ecomarket-facturas-archivo
$ aws s3api get-bucket-encryption --bucket ecomarket-facturas-archivo
$ aws s3api get-bucket-lifecycle-configuration --bucket ecomarket-facturas-archivo
$ aws s3api get-bucket-policy --bucket ecomarket-facturas-archivoIf get-bucket-lifecycle-configuration returns a policy and you have not imported aws_s3_bucket_lifecycle_configuration, you are missing a resource. The plan will still be clean, because Terraform does not manage what is not declared, and that configuration will remain as permanent, undocumented drift.
Level 3: the acid test.
Not to run it — never in production — but to count. If the number does not match what you expect, either resources are missing from the import or too many have been imported.
The tags_all and default tags trap
With default_tags configured, the plan after an import will always want to add those tags, because the imported resource does not have them:
~ resource "aws_s3_bucket" "invoices" {
~ tags_all = {
+ "ManagedBy" = "terraform"
+ "Project" = "ecomarket"
# (2 unchanged elements hidden)
}
}This is not a problem: it is correct and desirable. An adopted resource should end up tagged as managed by Terraform. But it has to be told apart from a real change, and it has to be applied consciously. The clean sequence is:
- Import with configuration that reproduces the current state → a zero-change plan.
- In another pull request, add the project tags → a plan with one expected change.
The list ordering trap
Some list-typed attributes come back from the API in a different order from the one you wrote:
~ resource "aws_lb" "secondary" {
~ subnets = [
- "subnet-0b2c...",
- "subnet-0a1b...",
+ "subnet-0a1b...",
+ "subnet-0b2c...",
]
}The same values, a different order. For attributes the provider models as sets, Terraform does not show this change. For the ones it models as lists, it does, and it is a false positive. The fix is to order your expression the same way the API does, or to use sort() if the attribute tolerates it.
- Bulk importing
When hundreds of resources have to be adopted, importing one at a time does not scale. But automated tools carry real risks.
Strategy: small batches
EcoMarket's rule: batches of 5 to 15 resources, grouped by component, one pull request per batch.
flowchart TD
A["Complete inventory<br/>of what is there"] --> B["Group by component<br/>network, data, app, IAM"]
B --> C["Order by dependency<br/>network first, app after"]
C --> D["Batch 1: the VPC and its subnets"]
D --> E["import blocks + configuration"]
E --> F["plan: N to import, 0 to change"]
F --> G["apply + three-level verification"]
G --> H["Clean-up pull request:<br/>remove the import blocks"]
H --> I{"Any batches left?"}
I -->|"Yes"| J["Next batch"]
J --> E
I -->|"No"| K["plan -destroy to count:<br/>is everything there?"]
Why small batches:
| Reason | Detail |
|---|---|
| The plan is reviewable | Nobody really reviews a plan with 200 imports |
| Failure is contained | If an ID is wrong, you know which one |
| Rollback is feasible | Undoing 10 imports is workable; 200 is not |
| Dependency order is respected | Importing a subnet before its VPC produces dangling references |
| The team learns | The first batches teach the ID formats and the provider's traps |
Generating the import blocks with a script
For large batches, the blocks are generated from the inventory:
#!/usr/bin/env bash
# tools/generate-subnet-imports.sh
set -euo pipefail
VPC_ID="vpc-0a1b2c3d4e5f67890"
echo "# Generated by generate-subnet-imports.sh on $(date -I)"
echo "# REVIEW before applying: check that each ID corresponds to the right zone."
echo
aws ec2 describe-subnets \
--filters "Name=vpc-id,Values=${VPC_ID}" "Name=tag:Tier,Values=private" \
--query 'Subnets[].{id:SubnetId, zone:AvailabilityZone, cidr:CidrBlock}' \
--output json |
jq -r '.[] | @text "
import {
to = aws_subnet.private[\"\(.zone)\"]
id = \"\(.id)\" # real CIDR: \(.cidr)
}"'The comment with the real CIDR is deliberate: it lets you verify at a glance that the CIDR your configuration computes with cidrsubnet matches the one the subnet actually has. If it does not match, the plan would propose replacing it.
terraformer and the providers' generators
There are tools that walk an account and generate configuration and state:
| Tool | What it does | Risks |
|---|---|---|
| terraformer (Google, community) | Scans an account and generates .tf + state |
Low-quality configuration; outdated provider versions; it writes state directly |
The providers' own generators (aztfexport for Azure) |
Export a resource group | Better quality than terraformer, more limited |
-generate-config-out (native) |
Generates configuration for whatever you point at | Experimental, but it is HashiCorp's and it does not write state without an apply |
The risks of automated tools, in order of severity:
- They write the state without your seeing a plan. That is the opposite of the review principle everything else rests on.
- They generate unreadable code: thousands of lines with every default value, no references between resources, no modules, no variables. Turning that into maintainable code costs more than writing it.
- They import things you did not want to manage: resources managed by other teams, resources belonging to managed services, resources belonging to another tool. And one resource in two states is the disaster from section 13.
- They fall behind: they use old provider versions and generate obsolete syntax (for example, inline
ingressblocks instead of rules as resources, or the monolithicaws_s3_bucketfrom before the split into six resources).
When they are reasonable: for generating an inventory and a first approximation that you then rewrite by hand, in a development account, without applying the state they produce. As a discovery tool, they are fine; as a generator of the definitive configuration, they are not.
- Command, block or generation: which to use
| Criterion | The import command |
The import block |
Block + -generate-config-out |
|---|---|---|---|
| Minimum version | Any | 1.5 | 1.6 |
| Requires writing configuration first | Yes | Yes | No |
| Reviewed in a pull request | No | Yes | Yes |
| Appears in the plan | No | Yes | Yes |
| Reversible before applying | No | Yes | Yes |
| Runnable in the pipeline | With a separate manual step | Yes | With a review afterwards |
| Several resources | One command each | Several blocks or for_each |
The same |
| Shell escaping | Yes, and it is awkward | No | No |
| Configuration quality | Whatever you write | Whatever you write | Poor: it has to be cleaned up |
| When to use it | An emergency, a one-off resource, an old Terraform | By default | Discovering the attributes of something you do not know |
The practical recommendation for EcoMarket:
- An
importblock with-generate-config-outto explore an unknown resource and see which attributes it has. - Rewrite the configuration by hand from what was generated, with references, tags and
lifecycle. - An
importblock in the pull request, with theN to import, 0 to change, 0 to destroyplan pasted into the description. - A second pull request that removes the blocks and must give
No changes. - The
terraform importcommand is left for the emergency case: recovering a resource lost from the state with theapplybroken and people waiting.
- The three serious risks
13.1 Importing the wrong resource
Terraform imports the staging database under the address your production configuration uses. The next plan compares the production configuration against the staging instance and proposes modifying it so that it looks like production: changing its class, enabling Multi-AZ, changing its maintenance window. And if any immutable attribute differs, it proposes destroying and recreating it.
Safeguards:
- The
importblock shows the plan before applying. Read it: theidis right there. - An account guard like the one in 05-01 prevents importing from the wrong account.
- Verify the ID with the CLI before writing it, rather than copying it from a chat message.
13.2 The same resource in two states
This is the worst one, and the easiest to cause in a large organisation.
If team A imports the invoices bucket into the ecomarket-infra state and team B imports it into the administration-infra state, both states believe they manage the same object.
What happens next:
| Moment | What occurs |
|---|---|
| Team A applies a tag change | The bucket ends up with A's tags |
Team B runs plan |
It sees drift: the tags are not theirs. It proposes reverting them |
| Team B applies | The bucket goes back to B's tags |
Team A runs plan |
It sees drift. It proposes reverting |
| Steady state | Two states fighting over the same object, indefinitely |
And the ending that really hurts: somebody on team B removes the bucket from their configuration and applies. Terraform destroys it, because from their state that is what it means. Seven years of invoices with a legal retention obligation disappear, and team A does not find out until their next plan proposes creating a new bucket.
Safeguards:
| Safeguard | How |
|---|---|
| One owner per resource, written down | A ManagedBy = "terraform" tag plus Repo = "ecomarket-infra" on every resource |
| Search before importing | grep -r "<id or name>" across all the organisation's infrastructure repositories |
prevent_destroy on the irreplaceable |
It does not prevent the conflict, but it does prevent the ending |
| Separation by account | Two teams that do not share an account cannot overlap |
| Scheduled drift detection | A daily plan that raises an alert (module 8) catches the fight within 24 hours |
The prior check is literally this one, and it should be mandatory before any import:
# Is somebody else already managing this resource?
$ aws s3api get-bucket-tagging --bucket ecomarket-facturas-archivo | jq '.TagSet'
[
{"Key": "Departamento", "Value": "Administracion"},
{"Key": "Retencion", "Value": "7-anios"}
]
# No ManagedBy and no Repo: nobody manages it with Terraform. Clear to proceed.13.3 Accidental deletion while adjusting the configuration
The "adjust until the plan is clean" phase is where the accidents happen, because it is tempting to apply just to see what happens.
# aws_db_instance.invoices must be replaced
-/+ resource "aws_db_instance" "invoices" {
~ engine_version = "14.10" -> "15.4" # forces replacement
~ identifier = "facturas-db" -> "ecomarket-prod-facturas" # forces replacement
}
Plan: 1 to add, 0 to change, 1 to destroy.must be replaced after an import always means the same thing: your configuration does not describe the resource that is there. The correct response is to adjust the configuration to reality, never to apply.
The three safeguards, in order of effectiveness:
1. prevent_destroy from the very first block you write, even before importing:
resource "aws_s3_bucket" "invoices" {
bucket = "ecomarket-facturas-archivo"
lifecycle {
prevent_destroy = true
}
}With that in place, an apply that tries to destroy it fails before calling the API:
╷
│ Error: Instance cannot be destroyed
│
│ on invoices.tf line 1:
│ 1: resource "aws_s3_bucket" "invoices" {
│
│ Resource aws_s3_bucket.invoices has lifecycle.prevent_destroy set, but the
│ plan calls for this resource to be destroyed.
╵2. An automatic destruction check in the pipeline, the same one from 05-01:
terraform plan -out=plan.tfplan -var-file=prod.tfvars
DESTROYS=$(terraform show -json plan.tfplan |
jq '[.resource_changes[] | select(.change.actions | index("delete"))] | length')
if [[ "$DESTROYS" -gt 0 ]]; then
echo "::error::The plan destroys ${DESTROYS} resources. Manual review required."
exit 1
fi3. A state backup before every batch:
With bucket versioning enabled (03-03), this is redundant, and even so it costs one second. Recovering a damaged state is the subject of 09-03.
Common Mistakes and Tips
Importing without having written the resource block. The command fails with does not exist in the configuration. It is the first stone everybody trips over.
Assuming the import ID is the ARN, or the other way round. It depends on the resource: the bucket goes by name, the database by identifier, the load balancer by full ARN. The documentation's "Import" section, always. And if you manage an equivalent resource, its id in the state gives you the exact format.
Applying a plan with must be replaced after an import. It means your configuration does not describe the real resource. Applying destroys what you have just adopted. prevent_destroy from minute one.
Importing the bucket and forgetting its five satellite resources. The plan comes out clean and the versioning, encryption and lifecycle configuration stays outside Terraform, with nothing to warn you. Comparing against the console is the only remedy.
Forgetting the provider on a resource in another region or account. The error says "not found" and the resource exists perfectly well where you are not looking.
Not quoting for_each addresses in the shell. terraform import aws_subnet.private["eu-west-1a"] ... without quotes produces Index value required. The import block avoids the problem entirely.
Leaving the import blocks in the repository indefinitely. Noise, and a hazard if somebody does a state rm. They are removed in a second pull request that must give No changes.
Taking the output of -generate-config-out as the final configuration. It brings every default value, literal references and empty blocks. It is a starting point for learning which attributes exist, not a result.
Importing blind with terraformer against a production account. It writes state with no plan, imports other teams' things and generates code nobody wants to maintain. As an inventory tool, fine; as a definitive generator, no.
Not checking whether another repository already manages that resource. One resource in two states is a permanent fight that ends with somebody destroying what another team believed was theirs. A grep across the infrastructure repositories and a look at the tags, before every import.
Trusting that a zero-change plan guarantees everything is fine. It only says that what Terraform manages matches. The resources you have not declared do not show up anywhere.
Tip: import in batches of 5 to 15 resources per pull request, grouped by component and in dependency order. Nobody reviews a plan with two hundred imports.
Tip: paste the import plan into the pull request description. Pasting the N to import, 0 to add, 0 to change, 0 to destroy gives the reviewer exactly what they need to approve in thirty seconds.
Exercises
Exercise 1: adopting the whole invoices bucket
The bucket ecomarket-facturas-archivo has existed since 2024 with this real configuration, obtained from the CLI:
{
"region": "eu-west-1",
"versioning": "Enabled",
"encryption": {"SSEAlgorithm": "AES256", "BucketKeyEnabled": true},
"public_access_block": {
"BlockPublicAcls": true, "IgnorePublicAcls": true,
"BlockPublicPolicy": true, "RestrictPublicBuckets": true
},
"lifecycle": [
{"ID": "archivar-antiguas", "Status": "Enabled",
"Filter": {"Prefix": ""},
"Transitions": [{"Days": 90, "StorageClass": "GLACIER"}]}
],
"tags": {"Departamento": "Administracion", "Retencion": "7-anios"}
}- Write the
importblocks and the complete configuration for all the necessary resources. - State the plan you expect to see and what you would do if
1 to changeappeared. - Add the safeguards appropriate to a bucket holding seven years of invoices with a legal retention obligation.
- Describe the three-level verification you would carry out afterwards.
Exercise 2: the small-hours load balancer
During an incident, a load balancer was created by hand with ARN arn:aws:elasticloadbalancing:eu-west-1:123456789012:loadbalancer/app/incidente-2026-03/9f8e7d6c5b4a3210. Nobody knows how it is configured.
- Write the sequence of commands and blocks to discover its configuration without touching the state.
- From the generated output in section 6, identify at least five things you would clean up and explain why.
- The load balancer has to end up inside the
appmodule, not in the root. Describe the sequence of pull requests. - On import, the plan shows
~ subnetswith the same values in a different order. Explain whether that is a problem and what you would do.
Exercise 3: the two-states disaster
The administration team has its own repository, administration-infra, and its own state. They have imported the bucket ecomarket-facturas-archivo without telling anyone. You imported it last week into ecomarket-infra.
- Describe the symptoms each team will observe over the next few days.
- Explain the worst possible ending, step by step.
- Propose the procedure for resolving it without destroying the bucket, saying which team does what and in what order.
- Propose three preventive controls so that it does not happen again, with the approximate cost of implementing each one.
Solutions
Solution 1
1. import blocks and complete configuration:
# infra/app/invoices.tf
# ─────────────────── Import blocks ───────────────────
# They all use the bucket NAME as the id: it is the format for every
# aws_s3_bucket_* resource.
import {
to = aws_s3_bucket.invoices
id = "ecomarket-facturas-archivo"
}
import {
to = aws_s3_bucket_versioning.invoices
id = "ecomarket-facturas-archivo"
}
import {
to = aws_s3_bucket_server_side_encryption_configuration.invoices
id = "ecomarket-facturas-archivo"
}
import {
to = aws_s3_bucket_public_access_block.invoices
id = "ecomarket-facturas-archivo"
}
import {
to = aws_s3_bucket_lifecycle_configuration.invoices
id = "ecomarket-facturas-archivo"
}
# ─────────────────── Configuration ───────────────────
resource "aws_s3_bucket" "invoices" {
bucket = "ecomarket-facturas-archivo"
# Reproduces the current tags EXACTLY. Adding the project's own
# tags goes in a second pull request, not this one.
tags = {
Departamento = "Administracion"
Retencion = "7-anios"
}
lifecycle {
prevent_destroy = true
}
}
resource "aws_s3_bucket_versioning" "invoices" {
bucket = aws_s3_bucket.invoices.id
versioning_configuration {
status = "Enabled"
}
}
resource "aws_s3_bucket_server_side_encryption_configuration" "invoices" {
bucket = aws_s3_bucket.invoices.id
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "AES256"
}
bucket_key_enabled = true
}
}
resource "aws_s3_bucket_public_access_block" "invoices" {
bucket = aws_s3_bucket.invoices.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
resource "aws_s3_bucket_lifecycle_configuration" "invoices" {
bucket = aws_s3_bucket.invoices.id
rule {
id = "archivar-antiguas"
status = "Enabled"
filter {
prefix = ""
}
transition {
days = 90
storage_class = "GLACIER"
}
}
}2. Expected plan and what to do if it does not match:
If 1 to change appeared, the procedure is:
- Read which attribute changes. Never apply just to see what happens.
- Look up the real value with the CLI:
aws s3api get-bucket-<whatever>. - Adjust the configuration so that it reproduces that value.
- Repeat the
planuntil it comes out clean.
The most likely candidates in this specific case: bucket_key_enabled, which is easy to forget; the filter { prefix = "" }, which some providers model differently from an absent filter; and tags, if there were some extra tag the inventory did not pick up.
If must be replaced appeared, stop immediately: an immutable attribute is written wrong. Here the only candidate would be bucket, and prevent_destroy would block it anyway.
3. Safeguards for a bucket with a legal obligation:
resource "aws_s3_bucket" "invoices" {
bucket = "ecomarket-facturas-archivo"
tags = { Departamento = "Administracion", Retencion = "7-anios" }
lifecycle {
# 1. Stops an apply destroying it, wherever it comes from.
prevent_destroy = true
}
}
# 2. Object Lock in compliance mode: not even the account administrator
# can delete an object before its retention expires.
# CAUTION: it can only be enabled when the bucket is CREATED. If the
# bucket does not have it (object_lock_enabled = false in the imported
# state), it cannot be added: you would have to create a new bucket and
# copy the objects. Verifying that is part of the adoption.
# 3. A bucket policy that denies deletion to everybody except a specific
# compliance role.
data "aws_iam_policy_document" "invoices_protection" {
statement {
sid = "DenyDeleteExceptCompliance"
effect = "Deny"
principals {
type = "AWS"
identifiers = ["*"]
}
actions = [
"s3:DeleteObject",
"s3:DeleteObjectVersion",
"s3:DeleteBucket",
"s3:PutBucketVersioning",
]
resources = [
aws_s3_bucket.invoices.arn,
"${aws_s3_bucket.invoices.arn}/*",
]
condition {
test = "StringNotLike"
variable = "aws:PrincipalArn"
values = ["arn:aws:iam::123456789012:role/ecomarket-compliance"]
}
}
}
# 4. Replication to another region, because "legal retention obligation"
# and "a single region" are not compatible.And two safeguards that are not Terraform but form part of the same decision: the destruction check in the pipeline, and a CloudTrail alert on any DeleteBucket or PutBucketVersioning in that account.
4. Three-level verification:
# ── Level 1: a zero-change plan
$ terraform plan -var-file=prod.tfvars -detailed-exitcode
No changes.
# ── Level 2: compare against reality, resource by resource
$ terraform state list | grep invoices
aws_s3_bucket.invoices
aws_s3_bucket_lifecycle_configuration.invoices
aws_s3_bucket_public_access_block.invoices
aws_s3_bucket_server_side_encryption_configuration.invoices
aws_s3_bucket_versioning.invoices
# Is there any bucket configuration that is NOT in that list?
$ aws s3api get-bucket-policy --bucket ecomarket-facturas-archivo
An error occurred (NoSuchBucketPolicy) # good: no policy to import
$ aws s3api get-bucket-replication --bucket ecomarket-facturas-archivo
An error occurred (ReplicationConfigurationNotFoundError) # good
$ aws s3api get-bucket-notification-configuration --bucket ecomarket-facturas-archivo
{} # good: empty
$ aws s3api get-bucket-logging --bucket ecomarket-facturas-archivo
{} # good
# ── Level 3: count the destructions (WITHOUT applying)
$ terraform plan -destroy -var-file=prod.tfvars 2>&1 | grep -c "invoices.*will be destroyed"
# It must fail because of prevent_destroy, which is exactly what we want:
# Error: Instance cannot be destroyedLevel 3 failing with prevent_destroy is the best possible confirmation that the protection works.
Solution 2
1. Discovering without touching the state:
# Option A: the AWS CLI, which touches nothing.
$ ARN="arn:aws:elasticloadbalancing:eu-west-1:123456789012:loadbalancer/app/incidente-2026-03/9f8e7d6c5b4a3210"
$ aws elbv2 describe-load-balancers --load-balancer-arns "$ARN"
$ aws elbv2 describe-listeners --load-balancer-arn "$ARN"
$ aws elbv2 describe-target-groups --load-balancer-arn "$ARN"
$ aws elbv2 describe-tags --resource-arns "$ARN"
$ aws elbv2 describe-load-balancer-attributes --load-balancer-arn "$ARN"# Option B: configuration generation. Only the import block,
# with no resource block.
# discovery.tf
import {
to = aws_lb.small_hours
id = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:loadbalancer/app/incidente-2026-03/9f8e7d6c5b4a3210"
}$ terraform plan -var-file=prod.tfvars -generate-config-out=discovered.tf
# No apply is run: the state is not touched.
# discovered.tf contains every real attribute.
# Afterwards, delete the discovery file so that it does not stay in the repo.
$ rm discovery.tfOption B is superior because it gives you the attributes with the names the Terraform provider uses, not the AWS API's, which differ.
2. Five things to clean up in the generated configuration:
| # | What | Why |
|---|---|---|
| 1 | security_groups = ["sg-0d4e5f6789a1b2c3"] → [aws_security_group.load_balancer.id] |
Without the reference, Terraform does not know about the dependency. If the group is recreated, the load balancer is not updated and the graph is wrong |
| 2 | The repeated subnet_mapping blocks → subnets = [for z, s in module.network.public_subnets : s.id] |
Literal values that do not follow the network if it changes, and a far more verbose way of writing it |
| 3 | Every default value (enable_http2 = true, idle_timeout = 60, desync_mitigation_mode, xff_header_processing_mode, and so on) |
They hide what has actually been configured. Keep only what departs from the default |
| 4 | access_logs { bucket = "" enabled = false } |
An empty, disabled block. Either delete it or — better — enable it pointing at the logs bucket, which is what a production load balancer should have |
| 5 | tags = {} |
An adopted resource must end up tagged: merge(local.common_tags, { Name = ..., Origin = "imported-incidente-2026-03" }) |
And a sixth that is not clean-up but a decision: enable_deletion_protection = false. A production load balancer should have it enabled, but changing it means the plan will not come out clean, so it goes in a later pull request.
3. Sequence of pull requests:
| Pull request | Content | Expected plan |
|---|---|---|
| 1. Discovery | None: it is done locally with -generate-config-out and nothing is pushed |
— |
| 2. Adoption in the root | import block + clean configuration reproducing the current state |
1 to import, 0 to change, 0 to destroy |
| 3. Clean-up | Remove the import block |
No changes |
| 4. Move into the module | moved block from aws_lb.small_hours to module.app.aws_lb.secondary + the module call |
0 to add, 0 to change, 0 to destroy + a move line |
| 5. Hardening | enable_deletion_protection = true, access_logs enabled, project tags |
1 to change — expected and deliberate |
Five small, reviewable pull requests instead of one large one. import and moved are never mixed on the same resource, nor is adoption mixed with hardening: each plan must be readable and approvable on its own.
4. The ~ subnets with the same values in a different order:
It is not a problem, it is a presentation false positive. It happens because subnets is modelled as a list and the API returns the subnets in a different order from the one your for expression over the map produces.
What to do:
- Verify that they are exactly the same values, not that one is missing or extra:
$ terraform state show aws_lb.small_hours | grep -A5 'subnets'
$ aws elbv2 describe-load-balancers --load-balancer-arns "$ARN" \
--query 'LoadBalancers[0].AvailabilityZones[].SubnetId' | sort-
If they are the same, applying is harmless: AWS treats a load balancer's subnets as a set and does nothing.
-
To make the plan genuinely clean, order the expression the same way the API does:
# The subnets map is walked by sorted key, so this produces a
# deterministic order that usually matches the API's.
subnets = [for z in sort(keys(module.network.public_subnets)) : module.network.public_subnets[z].id]- And if it persists and it bothers you,
lifecycle { ignore_changes = [subnets] }is the last resort, at the cost of Terraform no longer detecting a real change of subnets. It is not the first thing you try.
Solution 3
1. Symptoms over the next few days:
| Day | Team A (ecomarket-infra) |
Team B (administration-infra) |
|---|---|---|
| 1 | Applies the project tags. Zero-change plan afterwards | — |
| 2 | — | Runs plan. Sees tags it does not recognise: ManagedBy, Project, Repo. Puts them down to "somebody touching the bucket through the console" and reverts them |
| 3 | Its scheduled plan detects drift: its tags are missing. Puts them back |
— |
| 4 | — | Sees drift again. Starts getting suspicious |
| 5+ | Both plans show permanent changes; neither converges; the pipeline's drift detection warns every day in both repositories |
The characteristic symptom is drift that reappears right after being corrected, in two places, with opposite changes.
2. The worst ending, step by step:
- Team B decides the invoices bucket is no longer theirs: it has moved to the platform team.
- It removes the
resourceblock from its configuration and opens a pull request. - Its
plansays0 to add, 0 to change, 1 to destroy. From their point of view that is correct: they are giving up managing it. - Nobody notices that "giving up managing it" and "destroying it" are the same thing to Terraform. The right move would have been
removed { from = ..., destroy = false }orterraform state rm(03-05). - They apply. The bucket is destroyed.
- With versioning enabled and no Object Lock, S3 deletes the entire bucket: seven years of invoices with a legal retention obligation.
- Team A does not find out until its next
plan, which proposes creating a bucket it believed it already had. - Recovery depends on whether there was replication to another region. If there was not, there is no recovery.
3. Resolution procedure without destroying the bucket:
Zero: freeze. A message to both teams: nobody applies anything in either repository until this is resolved.
# ── Step 1: protect the object NOW, before discussing anything.
# This is done from the console or the CLI, not through Terraform.
$ aws s3api put-bucket-policy --bucket ecomarket-facturas-archivo \
--policy file://deny-delete.json
# ── Step 2: back up BOTH states.
# Team A:
$ terraform state pull > backup-ecomarket-infra-$(date +%F).tfstate
# Team B:
$ terraform state pull > backup-administration-infra-$(date +%F).tfstate
# ── Step 3: decide the owner. An organisational decision, not a technical one.
# Let us say: the platform team (A) keeps the bucket, because it already
# manages the rest of the storage and has the pipeline set up.
# ── Step 4: team B RELEASES the resource WITHOUT destroying it.
# The preferred option, declarative and reviewable in a pull request:# administration-infra: remove the resource block AND add this.
removed {
from = aws_s3_bucket.invoices
lifecycle {
destroy = false # ← THE LINE THAT DECIDES EVERYTHING
}
}$ terraform plan
# It must say: "will no longer be managed by Terraform, but will NOT be destroyed"
Plan: 0 to add, 0 to change, 0 to destroy.
$ terraform apply
# The alternative, imperative option, if you cannot wait for a pull request:
$ terraform state rm aws_s3_bucket.invoices
# ── Step 5: verify that the bucket STILL EXISTS.
$ aws s3api head-bucket --bucket ecomarket-facturas-archivo
# No output = it exists. This is the moment to breathe.
# ── Step 6: team A verifies that its state is still fine.
$ terraform plan -var-file=prod.tfvars -detailed-exitcode
No changes.
# ── Step 7: mark ownership in the tags, so that this is never
# ambiguous again.tags = merge(local.common_tags, {
Name = "ecomarket-facturas-archivo"
ManagedBy = "terraform"
Repo = "ecomarket-infra"
Contact = "[email protected]"
})Step 4 is the critical one. removed { destroy = false } or state rm release the resource without touching it. Simply deleting the resource block destroys it. That is the difference between a resolved incident and a disaster.
4. Three preventive controls:
| Control | How | Cost to implement | Effectiveness |
|---|---|---|---|
| 1. Mandatory ownership tags | The provider's default_tags with ManagedBy, Repo and Contact in both repositories, plus a pipeline check that rejects resources without Repo |
Low: an afternoon. You already have default_tags configured |
High: the conflict is visible when inspecting the resource, before importing |
| 2. A mandatory prior check in the import procedure | Before any import: look up the resource's tags and grep the identifier across all the organisation's infrastructure repositories. Written into the pull request checklist |
Very low: it is documentation and discipline | Medium-high: it depends on people following it |
| 3. Scheduled drift detection | A daily plan -detailed-exitcode in each repository that raises an alert in the team's channel when the exit code is 2 (module 8) |
Medium: one scheduled job per repository, plus the initial noise from legitimate drift | High as detection: it turns "we found out when the bucket was destroyed" into "we found out within 24 hours" |
And a fourth control, more expensive but definitive: separate by account. If the administration bucket lives in the administration account and the platform team has no credentials for it, the conflict is impossible by construction. It is the same isolation logic that led EcoMarket to have three accounts, one per environment (06-01).
Conclusion
Importing is the operation that connects the real world — where things get created by hand, in emergencies and before your repository existed — with the declarative one.
- Importing writes the state, not the configuration, and it does not touch the cloud. Those three statements explain the whole flow: you write the
.tfand the subsequentplanis the exam. - The import identifier depends on the resource type and there is no general pattern. AWS mixes names, IDs and full ARNs; Azure always uses the resource ID; GCP uses combinations of project, location and name. The best trick: look at the
idof an equivalent resource you already manage. - The
terraform importcommand writes the state immediately, one resource per invocation, with no prior plan, leaving no reviewable trace and with awkward shell escaping forfor_each. It is left for emergencies. - The 1.5
importblock is the default choice: it appears in the plan, it is reviewed in a pull request, it is applied from the pipeline, it acceptsfor_eachand — decisively — if you do not like the plan, you delete the block and nothing has happened. -generate-config-outis for discovering which attributes a resource you do not know has, not for generating definitive code. What it produces carries literal references, every default value and empty blocks.- Importing a resource is rarely importing one resource. An S3 bucket is six, and the zero-change plan does not warn you about the missing ones: only comparing against the console catches that.
- Attributes the API does not return — passwords, keys, secrets — end up empty silently. The first
planwants to write them, and if your variable does not hold the real value, you change the production password. importandmovedcombine so that you adopt first and organise later, always in separate pull requests.- Batches of 5 to 15 resources, grouped by component and in dependency order. Nobody reviews a plan with two hundred imports, and automated tools that write state with no plan are the opposite of the review principle.
- The three serious risks: importing the wrong resource, which the plan shows you before you apply; importing the same resource into two states, which produces a permanent fight and can end with somebody destroying what another team believed was theirs; and applying a
must be replacedduring the adjustments, whichprevent_destroyfrom minute one turns into an error rather than a loss.
With this lesson, EcoMarket no longer has infrastructure outside the state: the invoices bucket and the small-hours load balancer are adopted, with their configuration written and reviewed. One debt from module 5 remains, and it is the one that closes module 6.
The next lesson, Preconditions, Postconditions and check Blocks, formalises what we have so far been writing by hand. The account guard from 05-01, the health check with data "http" from 05-05, the user_data size precondition that turned up in the exercises of 06-02 and the workspace guard from 06-01 are all the same family of instruments, and it is time to see it in full: the spectrum running from validation to terraform test, what each piece checks and when it runs, the difference between what should break the plan and what should merely warn, and why an error message that interpolates the value it received and says what to do is worth more than ten pages of module documentation.
