Introduction
This article will detail how to use AWS AssumeRole with the AWS Terraform provider to connect to other AWS accounts via one AWS account. AWS AssumeRole allows an IAM user to use security credentials from one AWS account to request temporary security credentials to access other AWS accounts by assuming roles in those accounts. This allows an IAM user to access multiple AWS accounts without creating security credentials in each AWS account.
How can AssumeRole be used with the Terraform AWS Provider?
In the example below, Terraform will be configured to connect to AWS Account A, request temporary security credentials for AWS Account B, and then AssumeRole to assume a role in AWS Account B to manage the resources within AWS Account B. Terraform will only need the security credentials for AWS Account A even though it will manage resources in AWS Account B via AssumeRole.
-
The first thing that needs to be done is to create an IAM role within AWS Account B that Terraform will AssumeRole into.
-
From within the AWS console of AWS Account B, navigate to IAM > Roles > Create role > Another AWS account.
-
Enter the Account ID of Account A (the account Terraform will call AssumeRole from).
-
(Optional) Check the box for “Require external ID”. This ensures requests coming from Account A can only use AssumeRole if these requests pass the specified external ID.
-
(Optional) Check the box for “Require MFA”. This ensures requests coming from Account A can only use AssumeRole if the IAM user has authenticated via MFA.
-
-
Next, the AWS Terraform provider must be configured to use AssumeRole. The code snippet below shows how to configure Terraform to connect to AWS Account A and AssumeRole into a role within AWS Account B.
provider "aws" {
# The security credentials for AWS Account A.
access_key = "AKIAXXXXXXXXXXXXXXXX"
secret_key = "123XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
region = "us-east-1"
# (Optional)Session Token obtained from sts:GetSessionToken or sts:AssumeRole When MFA is configured.
token = "AWS_SESSION_TOKEN"
assume_role {
# The role ARN within Account B to AssumeRole into. Created in step 1.
role_arn = "arn:aws:iam::01234567890:role/role_in_account_b"
# (Optional) The external ID created in step 1c.
external_id = "my_external_id"
}
}
-
Initialize Terraform using Terraform CLI or via Terraform Enterprise.
-
Attempt to create a test resource and verify that the resource has been created in AWS Account B.