Is there a way to export an AWS CLI Profile to Environment Variables?
you could use the following command to set your environment variable
aws configure get default.aws_access_key_id
aws configure get default.aws_secret_access_key
if you have another profile you can change, another way to write is
aws configure get aws_access_key_id --profile <new_profile>
aws configure get aws_secret_access_key --profile <new_profile>
so for example it would be
export TF_VAR_access_key=`aws configure get default.aws_access_key_id`
In Terraform
Terraform actually directly supports AWS CLI profiles: just set an appropriate profile
attribute in the aws
provider block.
Something like this should do the trick:
provider "aws" {
profile = "my_profile"
}
Environment variables
If you are instead in a situation in which you have to use environment variables Frederic's suggestion can be used this way:
export AWS_ACCESS_KEY_ID=$(aws configure get my_profile.aws_access_key_id)
export AWS_SECRET_ACCESS_KEY=$(aws configure get my_profile.aws_secret_access_key)
If you want to pass environment vars to a script use:
AWS_ACCESS_KEY_ID=$(aws configure get my_profile.aws_access_key_id) \
AWS_SECRET_ACCESS_KEY=$(aws configure get my_profile.aws_secret_access_key) \
./script.sh
Environment variables with "assume role"
If you use profiles to assume a role specified in config field role_arn
, then things get a little trickier as the credentials are generated on the fly (and expire after a while).
But it's still feasible:
read AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN <<< \
$(aws sts assume-role \
--role-arn $(aws configure get my_profile.role_arn) \
--role-session-name my_profile_session --output text | \
awk '/^CREDENTIALS/ { print $2, $4, $5 }')