Execute Terraform apply with AWS assume role

后端 未结 4 1962
夕颜
夕颜 2021-02-02 01:11

I need to execute a Terraform template to provision infrastructure for an AWS account which I can access by assuming a role.

The problem I have now is I do not have an I

4条回答
  •  南笙
    南笙 (楼主)
    2021-02-02 01:23

    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")
    
    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

提交回复
热议问题