A convenience function to assume a IAM Role via STS before running a command.

Add the following to your ~/.zshrc (or equivalent) file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
function with-role {
    readonly role_arn=${1:?"The role_arn must be specified."}
    env -S $(
        aws sts assume-role \
        --role-arn ${role_arn} \
        --role-session-name ${USER} \
        | \
        jq -r '.Credentials | "
          AWS_ACCESS_KEY_ID=\(.AccessKeyId)
          AWS_SECRET_ACCESS_KEY=\(.SecretAccessKey)
          AWS_SESSION_TOKEN=\(.SessionToken)
        "'
    ) ${@:2}
}

This assumes that you have both the AWS CLI and jq installed.

Example usage:

with-role arn:aws:iam::123456789012:role/someSpecialRole aws s3 ls