Execute Terraform apply with AWS assume role
Looking at your policy of trust relationship in the other account, there's a condition applied multi factor authentication below highlighted. So User should 2 factor authenticated before assuming the role. Remove this condition and try to run code.
"Condition": {
"Bool": {
"aws:MultiFactorAuthPresent": "true"
}
}
You should be able to do it like this: In Terraform configure the aws provider to use your local shared_credentials_file
provider "aws" {
region = "us-east-1"
shared_credentials_file = "${pathexpand("~/.aws/credentials")}"
profile = "default"
assume_role {
role_arn = "arn:aws:iam::1234567890:role/OrganizationAccountAccessRole"
}
}
"profile" is a named profile in ~/.aws/credentials that has AWS Access keys. E.g.
[default]
region = us-east-1
aws_access_key_id = AKIAJXXXXXXXXXXXX
aws_secret_access_key = Aadxxxxxxxxxxxxxxxxxxxxxxxxxxxx
This is not an IAM user in the account you want to access. It's in the "source" account (you need keys at some point to access the AWS cli).
"assume_role.role_arn" is the role in the account you want to assume. The IAM user in "profile" needs to be allowed to assume that role.
I have a bulletproof solution anytime you want to run commands as a specific role (including other accounts). I assume you have the AWS CLI tools installed. You will also have to install jq (easy tool to parse and extract data from json), although you can parse the data any way you wish.
aws_credentials=$(aws sts assume-role --role-arn arn:aws:iam::1234567890:role/nameOfMyrole --role-session-name "RoleSession1" --output json)
export AWS_ACCESS_KEY_ID=$(echo $aws_credentials|jq '.Credentials.AccessKeyId'|tr -d '"')
export AWS_SECRET_ACCESS_KEY=$(echo $aws_credentials|jq '.Credentials.SecretAccessKey'|tr -d '"')
export AWS_SESSION_TOKEN=$(echo $aws_credentials|jq '.Credentials.SessionToken'|tr -d '"')
First line assigns the response from the aws sts
command and puts it in a variable.
Last 3 lines will select the values from the first command and assigned them to variables that the aws
cli uses.
Considerations:
If you create a bash script, add your terraform commands there as well. You can also just create a bash with the lines above, and run it with a '.' in front (ie: . ./get-creds.sh
). This will create the variables on your current bash shell.
Role expires, keep in mind that roles have expiration of usually an hour.
Your shell will now have the three variables AWS_ACCESS_KEY_ID
, AWS_SECRET_ACCESS_KEY
, AWS_SESSION_TOKEN
. This means that it will override your ~/.aws/credentials
. Easiest thing to do to clear this is to just start a new bash session.
I used this article as my source to figure this out: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html