Terraform Advanced — Importing Infrastructure Exercises

less than 1 minute read

Practice importing existing resources.


Exercise 1 — Import Block

Task: Write an import block to import an existing VPC with ID vpc-abc123 into aws_vpc.main.

Answer
import {
  to = aws_vpc.main
  id = "vpc-abc123"
}

resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"   # Must match actual
  tags       = { Name = "main-vpc" }
}

Exercise 2 — Generate Config

Task: Write the commands to auto-generate config for an imported resource.

Answer
# imports.tf
import {
  to = aws_vpc.main
  id = "vpc-abc123"
}
$ terraform plan -generate-config-out=generated.tf
$ cat generated.tf   # Review the generated config
$ terraform apply     # Import into state

Exercise 3 — Remove Without Destroy

Task: Remove aws_rds_cluster.legacy from Terraform without destroying the actual database.

Answer
# Terraform 1.7+
removed {
  from = aws_rds_cluster.legacy
  lifecycle {
    destroy = false
  }
}
# Or with CLI
$ terraform state rm aws_rds_cluster.legacy

Chapter Summary

  • terraform import CLI: one resource at a time, manual config writing
  • import block: declarative, plan-able, supports for_each
  • -generate-config-out: auto-generates HCL from actual resource state
  • Bulk import: script + import blocks, or Terraformer
  • removed block: removes from state without destroying the resource

← The removed Block Chapter 7: Meta-Arguments →

Updated: