terraform: Import existing resources for terraform to manage them

3 min read

If we have some of the infrastructure that were created manually we can still import it into the terraform state. This ensures you can have a smooth transition from manually created resources to Infrastructure as Code

To do so we will be using then terraform import command:

$ terraform import
The import command expects two arguments.
Usage: terraform import [options] ADDR ID

(...)

Before importing a given resource, we will need to create its configuration in the root module. For example, we are going to import an IAM role using:

resource "aws_iam_role" "demo_iam_role" {
  name                  = "demo_iam_role"
  path                  = "/"
}

To import the resource we will also need to check the terraform documentation for the ID of the resource to import. For example, an IAM role can be imported using it's name

Once we have the ID an the resource defined on the root module we can use terraform import as follows:

$ terraform import aws_iam_role.demo_iam_role demo_iam_role
Acquiring state lock. This may take a few moments...
aws_iam_role.demo_iam_role: Importing from ID "demo_iam_role"...
aws_iam_role.demo_iam_role: Import prepared!
  Prepared aws_iam_role for import
aws_iam_role.demo_iam_role: Refreshing state... [id=demo_iam_role]

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.

Releasing state lock. This may take a few moments...

Other resources like aws_iam_role_policy_attachment uses a composite ID for importing the resource: they can be imported using the role name and policy arn separated by a slash.

Again, first we will have to define the resource in the root module:

resource "aws_iam_role_policy_attachment" "demo_policy" {
  role       = "demo_iam_role"
  policy_arn = aws_iam_policy.demo_policy.arn
}

To be able to use the terraform import command:

$ terraform import aws_iam_role_policy_attachment.demo_policy demo_iam_role/arn:aws:iam::123456789012:policy/demo_policy
Acquiring state lock. This may take a few moments...
aws_iam_role_policy_attachment.demo_policy: Importing from ID "demo_iam_role/arn:aws:iam::123456789012:policy/demo_policy"...
aws_iam_role_policy_attachment.demo_policy: Import prepared!
  Prepared aws_iam_role_policy_attachment for import
aws_iam_role_policy_attachment.demo_policy: Refreshing state... [id=demo_iam_role-arn:aws:iam::123456789012:policy/demo_policy]

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.

Releasing state lock. This may take a few moments...

Once these resources have been imported to the terraform state we will be able to move them to any module we are using.


Posted on 04/05/2021

Categories