DEV Community

Thomas H Jones II
Thomas H Jones II

Posted on • Originally published at thjones2.blogspot.com on

Crib Notes: Assuming a Role

Several of my current customers leverage AWS IAM's role-assumption capability. In particular, one of my customers leverages it for automating the execution of the Terragrunt-based IaC. For the automated-execution, they run the Terragrunt code from an EC2 that has an attached IAM role that allows code executed on the hosting-EC2 to assume roles in other accounts.

Sometimes, when writing updates to their Terragrunt code, it's helpful to be able to audit the target account's state before and after the execution, but outside the context of Terragrunt, itself. In these cases, knowing how to use the AWS CLI to switch roles can be quite handy. A quick one-liner template for doing so looks like:

$ eval "$(
aws sts assume-role \
  --role-arn "arn:<AWS_PARTITION>:iam::<TARGET_ACCOUNT_NUMBEr>:role/<TARGET_ROLE_NAME>" \
  --role-session-name <userid> --query 'Credentials' | \
awk '/(Key|Token)/{ print $0 }' | \
sed -e 's/",$/"/' \
    -e 's/^\s*"/export /' \
    -e 's/": "/="/' \
    -e 's/AccessKeyId/AWS_ACCESS_KEY_ID/' \
    -e 's/SecretAccessKey/AWS_SECRET_ACCESS_KEY/' \
    -e 's/SessionToken/AWS_SESSION_TOKEN/'
)"
Enter fullscreen mode Exit fullscreen mode

What the above does is:

  1. Opens a subshell to execute a series of commands in
  2. Executes aws sts assume-role to fetch credentials, in JSON format, for accessing the target AWS account as the target IAM role
  3. Uses awk to select which parts of the prior command's JSON output to keep (grep or others are likely more computationally-efficient, but you get the idea)
  4. Uses sed to convert the JSON parameter/value pair-strings into BASH-compatible environment-variable delcarations
  5. Uses eval to take the output of the subshell and read it into the current shell's environment

Once this is executed, your SHELL will grant you privileges to execute commands in the target account – be that using the AWS CLI or any other tool that understands the "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY" and "AWS_SESSION_TOKEN" environment variables.

Using aws sts get-caller-identity will allow you to see your new IAM role.

Top comments (0)