Terraform
Terraform
June 22, 2023

Terraform Import Block - New Terraform Feature

By
Ryan Fee

The Terraform import block, which was introduced in Terraform v 1.5.0, has made importing resources into Terraform much simpler. Rather than using the terraform import command, you can now simply add the block to your Terraform code and actually import resources during an apply.

The main advantage to using the import block is that you’re seeing the output of the Terraform plan prior to modifying your state. Previously, with the import command, you were kind of blindly modifying state and hoping for the best. Now, with the plan output you know exactly what is going to happen with your state, just like any other Terraform run.

Also, if you’re using a remote backend, like Scalr or Terraform Cloud, this makes it easier to do the import as you don’t have to specify something like a custom hook or any other workaround to do the import.

Below is a simple example of importing an ec2 instance into state.

I am first going to define the import block with reference to the provider resource (or module) that you want the instance to be imported to:

import {
  to = aws_instance.scalr
  id = "i-09d83481c58338f91"
}

Now, you’ll need to define the Terraform code that the import block is reference:

resource "aws_instance" "scalr" {
  ami                    = "ami-12345"
  instance_type          = "t2.nano"
  subnet_id              = "subnet-12345"
  vpc_security_group_ids = ["sg-12345"]
  key_name               = "some_key"
}

Where the full main.tf is:

import {
  to = aws_instance.scalr
  id = "i-09d83481c58338f91"
}

resource "aws_instance" "scalr" {
  ami                    = "ami-12345"
  instance_type          = "t2.nano"
  subnet_id              = "subnet-12345"
  vpc_security_group_ids = ["sg-12345"]
  key_name               = "some_key"
}

Now all you have to do is run your standard Terraform commands and the resources will be imported upon an apply:

terraform apply

Waiting for the plan to start...

Terraform v1.5.0
Initializing Terraform configuration...
Configuring remote state backend...
Initializing plugins and modules...

------------------------------------------------------------------------

aws_instance.scalr: Preparing import... [id=i-09d83481c58338f91]
aws_instance.scalr: Refreshing state... [id=i-09d83481c58338f91]

Terraform will perform the following actions:

  # aws_instance.scalr will be imported
…
..
.

Apply complete! Resources: 1 imported, 0 added, 0 changed, 0 destroyed.

That’s it! With just a few lines of code we have imported the resources in a safer and more predictable way. Get started using the Import Block feature in Scalr today!

Start using the Terraform platform of the future.

A screenshot of the modules page in the Scalr Platform