AWSAWS IAMaws_iam_rolePro

How to Import an AWS IAM Role into Terraform

To import an existing AWS IAM Role into Terraform, scan it with Terraback and run terraback aws import --method bulk. Terraback writes the matching aws_iam_role resource block and the Terraform 1.5+ import block for you, so you do not have to run terraform import by hand. The import ID is the role name (for example, app-execution-role).

Import AWS IAM Role with Terraback (recommended)

Terraback reverse-engineers your live infrastructure: it reads the AWS IAM resource with read-only credentials, generates the HCL, and produces the exact import block. Two commands take you from a live AWS IAM Role to managed Terraform.

1

Scan your AWS account

terraback scan all aws --region us-east-1
2

Generate import blocks and import into state

terraback aws import --method bulk

The Terraform import block

Terraback emits a Terraform 1.5+ import block like the one below. Because the block lives in your configuration, the import is reviewable in a pull request and repeatable across environments.

import {
  to = aws_iam_role.app
  id = "app-execution-role"
}

Example aws_iam_role configuration

Here is a realistic AWS IAM Role block. Terraback generates a fuller version from your actual resource attributes; this is a minimal, valid starting point.

resource "aws_iam_role" "app" {
  name = "app-execution-role"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Action    = "sts:AssumeRole"
      Effect    = "Allow"
      Principal = { Service = "ec2.amazonaws.com" }
    }]
  })
}

Gotchas when importing a AWS IAM Role

  • Import the role by name, not by ARN.
  • Managed policy attachments import as separate aws_iam_role_policy_attachment resources; inline policies as aws_iam_role_policy.
  • The assume_role_policy JSON must match the live trust policy exactly or Terraform plans an update on the first apply.
  • IAM is global, so no region is required, but the role name must be unique within the account.

Doing it manually with terraform import

The native approach is to write the aws_iam_role block by hand, then run terraform import aws_iam_role.example <import-id> for every resource, one at a time. That works for a handful of resources, but it does not scale: you author all the HCL yourself and repeat the command for each item. Terraback generates the HCL and the import blocks for your whole account in one pass.

Import your whole AWS account in minutes

Terraback scans 80+ AWS resource types and emits clean Terraform plus import blocks, running locally with read-only credentials. $499 once, no SaaS.