Skip to main content

Infrastructure as code · Intermediate · 22 min

Bring existing cloud resources under Terraform with import blocks

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Terraform 1.17.2 · hashicorp/aws 6.74 · AWS CLI 2.42.4

You will adopt an S3 bucket and a security group that were made by hand, generate their Terraform code, clean it up until the plan is empty, import a batch of buckets with for_each, and compare the result with the older terraform import command.

On this page

Most teams start Terraform after something already exists. A bucket was made in the console during a launch week, a security group was added by hand to unblock a demo, and now nobody is sure which settings are deliberate. Writing a fresh resource block for them does not help: Terraform would try to create a second bucket with the same name and fail.

Importing tells Terraform "this object already exists, track it at this address". Since Terraform 1.5 you do that with an import block in your code. Terraform reads the real object during a plan, shows you what it found, and only records it in state when you apply. Because the import is code, it goes through the same pull request and plan review as every other change.

In this tutorial you will:

  • create a bucket and a security group outside Terraform, the way someone might have in the console
  • write import blocks for them and let Terraform generate starting code with -generate-config-out
  • clean the generated code: drop arguments that only repeat defaults, and swap hard-coded IDs for references
  • apply until terraform plan reports no changes
  • import three more buckets with one import block and for_each
  • use the older terraform import command once, to see what import blocks improve on

The demo lives in ~/import-demo. Everything you create here is an empty S3 bucket or a security group. Neither bills while it stays like that: S3 charges for stored data and requests, and AWS does not charge for security groups. The last step deletes all of it.

Step 1 · Install Terraform 1.17 and the AWS CLI

Install curl and unzip, then download Terraform 1.17.2 for your machine's architecture, check it against HashiCorp's published checksums and put it on your PATH:

Bash
sudo apt update
sudo apt install -y curl unzip ca-certificates
TF_VERSION=1.17.2
ARCH=$(dpkg --print-architecture)
cd "$(mktemp -d)"
curl -fsSLO "https://releases.hashicorp.com/terraform/${TF_VERSION}/terraform_${TF_VERSION}_linux_${ARCH}.zip"
curl -fsSLO "https://releases.hashicorp.com/terraform/${TF_VERSION}/terraform_${TF_VERSION}_SHA256SUMS"
sha256sum --ignore-missing -c "terraform_${TF_VERSION}_SHA256SUMS"
unzip -o "terraform_${TF_VERSION}_linux_${ARCH}.zip" terraform
sudo install -m 0755 terraform /usr/local/bin/terraform
terraform version

Now install version 2.42.4 of the AWS CLI from Amazon's versioned installer. uname -m prints x86_64 or aarch64, which matches Amazon's file names:

Bash
AWS_CLI_VERSION=2.42.4
curl -fsSLo awscliv2.zip "https://awscli.amazonaws.com/awscli-exe-linux-$(uname -m)-${AWS_CLI_VERSION}.zip"
unzip -q -o awscliv2.zip
sudo ./aws/install
aws --version

If the AWS CLI is already installed, the installer stops and tells you so. Run sudo ./aws/install --update instead. Neither tool gets updates from apt: to upgrade later, run the same commands with a newer version number.

The AWS provider is a large download. If you pay for data by the megabyte, on a prepaid bundle for example, set a plugin cache now so every project on the machine shares one copy:

Bash
mkdir -p ~/.terraform.d/plugin-cache
echo 'export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache"' >> ~/.bashrc
export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache"

Check it worked

sha256sum prints terraform_1.17.2_linux_amd64.zip: OK (or arm64). terraform version prints Terraform v1.17.2 on its first line, and aws --version starts with aws-cli/2.42.4.

Step 2 · Make two resources by hand

In a real account the resources you want to adopt already exist. To practise safely, make stand-ins in a sandbox account: a bucket for a reports site, and a security group that lets anyone reach it on port 443.

Point the AWS CLI at your sandbox account. If you use a named profile, run export AWS_PROFILE=<your-sandbox-profile> first (replace the placeholder); /tutorials/set-up-the-aws-cli-with-sso-and-named-profiles covers setting one up. Then confirm who you are:

Bash
aws sts get-caller-identity

The output shows the account ID and the user or role you are signed in as. Check that it is the sandbox account before you go on.

Bucket names are global across all AWS accounts, so add a random suffix to yours. Create the project folder and a small demo.env file that holds the suffix and the Region, so later commands can read them back:

Bash
mkdir -p ~/import-demo
cd ~/import-demo
SUFFIX=$(head -c 4 /dev/urandom | od -An -tx1 | tr -d ' \n')
cat > demo.env <<EOF
export AWS_REGION=eu-west-2
export SUFFIX=${SUFFIX}
EOF
. ./demo.env
echo "Your suffix is ${SUFFIX}"

The examples use eu-west-2 (London). Any Region works if you use it everywhere. If you are in Africa and your account has the Cape Town Region (af-south-1) enabled, it is closer to you; it is an opt-in Region, so it must be turned on in the account before you can use it.

Now make the bucket, and a security group in the account's default VPC with one rule for HTTPS:

Bash
aws s3api create-bucket --bucket "import-demo-${SUFFIX}-site" \
  --create-bucket-configuration LocationConstraint="$AWS_REGION"

VPC_ID=$(aws ec2 describe-vpcs --filters Name=is-default,Values=true \
  --query 'Vpcs[0].VpcId' --output text)
SG_ID=$(aws ec2 create-security-group --group-name import-demo-web \
  --description "HTTPS from anywhere for the reports site" \
  --vpc-id "$VPC_ID" --query GroupId --output text)
aws ec2 authorize-security-group-ingress --group-id "$SG_ID" \
  --ip-permissions 'IpProtocol=tcp,FromPort=443,ToPort=443,IpRanges=[{CidrIp=0.0.0.0/0,Description=HTTPS}]'
echo "export SG_ID=${SG_ID}" >> demo.env
echo "VPC ${VPC_ID}, security group ${SG_ID}"

If VPC_ID comes back as None, the account has no default VPC. Create one with aws ec2 create-default-vpc and run the block again.

Check it worked

aws s3api head-bucket --bucket "import-demo-${SUFFIX}-site" returns without an error. aws ec2 describe-security-groups --group-ids "$SG_ID" shows import-demo-web with one inbound rule for TCP port 443. cat demo.env shows three export lines.

Step 3 · Write import blocks and generate the code

An import block needs two things: to, the address the object will have in Terraform, and id, the identifier the provider uses to find it. For an S3 bucket the ID is the bucket name. For a security group it is the group ID, such as sg-0abc....

Create the configuration: the Terraform and provider versions, the provider itself, two variables, a local for naming and the import blocks. There are no resource blocks yet; Terraform will write those:

Bash
cd ~/import-demo
. ./demo.env

cat > versions.tf <<'HCL'
terraform {
  required_version = "~> 1.17.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.74"
    }
  }
}
HCL

cat > providers.tf <<'HCL'
provider "aws" {
  region = var.aws_region
}
HCL

cat > variables.tf <<'HCL'
variable "aws_region" {
  type        = string
  description = "AWS Region the hand-made resources live in."
  default     = "eu-west-2"
}

variable "suffix" {
  type        = string
  description = "Random suffix that keeps the demo bucket names unique."
}

variable "web_sg_id" {
  type        = string
  description = "ID of the security group made by hand."
}
HCL

cat > locals.tf <<'HCL'
locals {
  prefix      = "import-demo-${var.suffix}"
  site_bucket = "${local.prefix}-site"
}
HCL

cat > terraform.tfvars <<EOF
aws_region = "${AWS_REGION}"
suffix     = "${SUFFIX}"
web_sg_id  = "${SG_ID}"
EOF

cat > imports.tf <<'HCL'
import {
  to = aws_s3_bucket.site
  id = local.site_bucket
}

import {
  to = aws_security_group.web
  id = var.web_sg_id
}
HCL

terraform.tfvars holds the values for this account only. Nothing in it is secret, but it is specific to you, so it is a file many teams keep out of Git and pass in some other way.

Initialise the project, then ask Terraform to plan the imports and write code for anything that has no resource block. The file you name must not exist yet:

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

Terraform warns that config generation is experimental, which it has been since 1.5. That is a warning about the format of the file it writes, not about the import itself.

The plan may also stop with errors that point at generated.tf, such as "name": conflicts with name_prefix or Can't configure a value for "arn". That is expected. The generator copies every value it read, including some the provider will not accept back, and it still writes the file. You fix those lines in the next step.

Check it worked

The plan lists aws_s3_bucket.site will be imported and aws_security_group.web will be imported, each marked (config will be generated). It ends either with something like Plan: 2 to import, 0 to add, 0 to change, 0 to destroy. or with errors about lines in generated.tf. Either way a new file, generated.tf, holds one resource block for each.

Step 4 · Clean up the generated code

Open the file and read it:

Bash
cat generated.tf

Terraform writes every argument the provider will accept, filled in with the value it found. That makes a faithful snapshot, but poor code to maintain. You will see things like these (the exact list depends on the provider version):

  • Arguments that repeat a default, such as force_destroy = false, object_lock_enabled = false, revoke_rules_on_delete = false and tags = {}. They add nothing.
  • Read-only attributes, such as arn and owner_id. AWS sets these, and they are what the plan's Can't configure a value errors were about. They must go.
  • Both name and name_prefix, which cannot be set together. Keep name.
  • Arguments set to null, such as bucket_prefix = null and name_prefix = null. They mean "not set" and can go.
  • region, which provider 6.x lets you set per resource. Leave it out and the resource uses the provider's Region.
  • Hard-coded identifiers: the bucket name as a literal string, and vpc_id = "vpc-...". These are the ones that matter. If the VPC is rebuilt or the code is reused in another account, a literal ID points at the wrong thing.
  • Rules as lists of objects, with every field spelled out, including empty lists such as ipv6_cidr_blocks = [].

Write the cleaned version into main.tf. It looks up the default VPC with a data source instead of a literal ID, names the bucket from the local you already have, and writes the rules as blocks with only the fields that carry meaning:

Bash
cat > main.tf <<'HCL'
data "aws_vpc" "default" {
  default = true
}

resource "aws_s3_bucket" "site" {
  bucket = local.site_bucket
}

resource "aws_security_group" "web" {
  name        = "import-demo-web"
  description = "HTTPS from anywhere for the reports site"
  vpc_id      = data.aws_vpc.default.id

  ingress {
    description = "HTTPS"
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}
HCL
rm generated.tf
terraform fmt
terraform plan -out=tfplan

The egress block matches the allow-all outbound rule that AWS adds to every new security group. Keep it: it records a rule that exists, and a reviewer can now see it.

Read the plan with one question in mind: does it change anything other than importing? If it shows ~ update in-place, an argument in main.tf disagrees with the real object. Look at the attribute it marks, then either fix your code to match, or decide the change is intended and say so in the pull request. If it shows must be replaced, stop: an argument such as name or vpc_id points at something else, and applying would delete the real security group and make a new one.

Check it worked

The plan still lists two imports, now without (config will be generated), and ends with Plan: 2 to import, 0 to add, 0 to change, 0 to destroy. ls shows main.tf and no generated.tf.

Step 5 · Apply the import until the plan is empty

Apply the saved plan. This writes the two objects into the state and changes nothing in AWS:

Bash
terraform apply tfplan
terraform state list
terraform plan

An import is finished when a normal plan, with no import pending, has nothing to do. If that last plan shows a change, go back to main.tf, adjust the argument it names and plan again. Repeat until it is clean. This loop is the real work of an import: each round teaches you something about how the resource was set up.

Check it worked

The apply ends with Apply complete! Resources: 2 imported, 0 added, 0 changed, 0 destroyed. terraform state list shows data.aws_vpc.default, aws_s3_bucket.site and aws_security_group.web. The final plan ends with No changes. Your infrastructure matches the configuration.

Step 6 · Import many resources with for_each

Say the same person also made a log bucket for each of three systems. One import block with for_each can adopt all of them, matching a resource block that uses the same for_each. Make the three buckets first:

Bash
cd ~/import-demo
. ./demo.env
for name in audit billing access; do
  aws s3api create-bucket --bucket "import-demo-${SUFFIX}-logs-${name}" \
    --create-bucket-configuration LocationConstraint="$AWS_REGION"
done

Terraform 1.17 does not generate code for an import block that uses for_each, so write the resource block yourself. The bucket you cleaned in the last step is your model. Put the list of names in a local, so the resource and the import block cannot drift apart:

Bash
cat > logs.tf <<'HCL'
locals {
  log_buckets = toset(["audit", "billing", "access"])
}

resource "aws_s3_bucket" "logs" {
  for_each = local.log_buckets
  bucket   = "${local.prefix}-logs-${each.key}"
}
HCL

cat >> imports.tf <<'HCL'

import {
  for_each = local.log_buckets
  to       = aws_s3_bucket.logs[each.key]
  id       = "${local.prefix}-logs-${each.key}"
}
HCL
terraform plan -out=tfplan
terraform apply tfplan

Inside an import block, each.key works as it does in a resource. Here each name becomes both the instance key, aws_s3_bucket.logs["audit"], and part of the bucket name. For a list you cannot work out from a pattern, use a map from key to ID instead, for example { audit = "old-audit-bucket-2023" }, with each.key in to and each.value in id.

Check it worked

The plan before the apply showed Plan: 3 to import, 0 to add, 0 to change, 0 to destroy., and the apply reports 3 imported. terraform state list now includes aws_s3_bucket.logs["access"], aws_s3_bucket.logs["audit"] and aws_s3_bucket.logs["billing"].

Step 7 · Compare with the terraform import command

Before Terraform 1.5 the only way in was the terraform import command. It still works, and you will meet it in older runbooks. Try it on one more hand-made bucket:

Bash
cd ~/import-demo
. ./demo.env
aws s3api create-bucket --bucket "import-demo-${SUFFIX}-archive" \
  --create-bucket-configuration LocationConstraint="$AWS_REGION"

cat > archive.tf <<'HCL'
resource "aws_s3_bucket" "archive" {
  bucket = "${local.prefix}-archive"
}
HCL

terraform import aws_s3_bucket.archive "import-demo-${SUFFIX}-archive"
terraform state list
terraform plan

It works: the bucket is in the state and the plan is clean. Compare how you got there:

  • There was no plan. The command wrote to the state the moment you ran it. With an import block you saw what Terraform found before anything was recorded, and you could have stopped.
  • Nobody could review it. A pull request shows archive.tf, but nothing in the code says the bucket was imported or which ID was used. An import block is a diff a colleague can read, and the plan in CI shows the import before it happens.
  • It only touches your state. If the same code runs against a staging and a production state, someone has to repeat the command for each one. An import block runs wherever the code is applied.
  • One resource per command, and no code. You had to write the resource block first, and three log buckets would have taken three commands with the right quoting for aws_s3_bucket.logs["audit"].

Keep the command for one-off repairs on a single state. Use import blocks for everything that goes through review.

Check it worked

terraform import ends with Import successful!. terraform state list shows aws_s3_bucket.archive, and the plan reports No changes.

Step 8 · Remove the import blocks, then clean up

Once every state that uses this code has applied the imports, the import blocks have done their job. Leaving them does no harm, because Terraform skips an import whose target is already in the state, but removing them keeps the code readable. Delete the file and confirm the plan stays clean:

Bash
cd ~/import-demo
rm imports.tf
terraform plan

That is where a real import ends: the resources stay, now managed in code. This demo goes one step further and deletes everything, so nothing is left in your sandbox account.

The next commands destroy the five buckets and the security group. In a real account that would delete the resources you just adopted, so run them only in the sandbox. Plan the destroy and read it before you apply it:

Bash
terraform plan -destroy -out=tfplan
terraform apply tfplan

Then delete the demo folder, which holds the state and demo.env. Check you are removing ~/import-demo and nothing else:

Bash
cd ~
rm -rf ~/import-demo

If you installed the tools only for this tutorial, remove Terraform, the plugin cache and the AWS CLI, and delete the TF_PLUGIN_CACHE_DIR line from ~/.bashrc:

Bash
sudo rm -f /usr/local/bin/terraform
rm -rf ~/.terraform.d/plugin-cache
sudo rm -rf /usr/local/aws-cli /usr/local/bin/aws /usr/local/bin/aws_completer

Check it worked

The plan after removing imports.tf reports No changes. The destroy ends with Destroy complete! Resources: 6 destroyed. aws s3api list-buckets --query 'Buckets[].Name' (run before you remove the CLI) no longer lists any import-demo- bucket, and ls ~/import-demo reports No such file or directory.

Next steps

  • Rename or reorganise the resources you imported without recreating them in /tutorials/move-resources-without-recreating-them-using-moved-blocks.
  • Move the state out of your laptop and into a shared, locked backend in /tutorials/terraform-1-17-remote-state-on-s3.
  • Stop an adopted bucket from being deleted by a careless change in /tutorials/protect-resources-with-lifecycle-rules-in-terraform.
  • Set up SSO profiles so every command in this tutorial uses short-lived credentials in /tutorials/set-up-the-aws-cli-with-sso-and-named-profiles.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.