assume-role

nicolaw 27th March 2020 at 9:38am
AWS

One-liner with jq

eval "$(aws sts assume-role --role-arn arn:aws:iam::1234567890:role/AdministratorAccess --role-session-name $(whoami)@$(hostname) | jq -r '.Credentials|{"AWS_ACCESS_KEY_ID":.AccessKeyId,"AWS_SECRET_ACCESS_KEY":.SecretAccessKey,"AWS_SESSION_TOKEN":.SessionToken}|to_entries|map("export \(.key)=\(.value|tostring|@sh)")|.[]')"

Manually with awscli

pip3 install awscli
STS="$(aws sts assume-role --role-arn "arn:aws:iam::1234567890:role/AdministratorAccess" --role-session-name "MyAdministratorAccessWoop")"
export AWS_ACCESS_KEY_ID="$(jq -r .Credentials.AccessKeyId <<< "$STS")"
export AWS_SECRET_ACCESS_KEY="$(jq -r .Credentials.SecretAccessKey <<< "$STS")"
export AWS_SESSION_TOKEN="$(jq -r .Credentials.SessionToken <<< "$STS")"

Micro shell script

#!/usr/bin/env bash
printf '# Usage: eval "$(%s <role-arn> [role-session-name])"\n' "$0"
AWS_SESSION_TOKEN="" aws sts assume-role --role-arn "${1:-arn:aws:iam::ACCOUNT-ID:role/ROLE}" --role-session-name "${2:-$(whoami)@$(hostname)}" | jq -r '.Credentials|{"AWS_ACCESS_KEY_ID":.AccessKeyId,"AWS_SECRET_ACCESS_KEY":.SecretAccessKey,"AWS_SESSION_TOKEN":.SessionToken}|to_entries|map("export \(.key)=\(.value|tostring|@sh)")|.[]'

Simple shell script

#!/usr/bin/env bash

assume-role () {
  declare account="" role=""
  if [[ $# -eq 2 ]] ; then
    account="$1"
    role="$2"
  elif [[ $# -eq 1 ]] ; then
    if [[ "$1" =~ ^arn:aws:iam::(.*):role/(.*)$ ]] ; then
      account="${BASH_REMATCH[1]}"
      role="${BASH_REMATCH[2]}"
    else
      account="$(aws sts get-caller-identity | jq -r .Account)"
      role="$1"
    fi
  else
    >&2 echo "Syntax: ${BASH_SOURCE[0]##*/} [account] <role>"
    return 64
  fi

  declare sts="" rc=0
  sts="$(aws sts assume-role \
      --role-arn "arn:aws:iam::$account:role/$role" \
      --role-session-name "$USER=$role@$account")" || rc=$?
  if [[ $rc -ne 0 ]] ; then
    return $rc
  fi

  export AWS_ACCESS_KEY_ID="$(jq -r .Credentials.AccessKeyId <<< "$sts")"
  export AWS_SECRET_ACCESS_KEY="$(jq -r .Credentials.SecretAccessKey <<< "$sts")"
  export AWS_SESSION_TOKEN="$(jq -r .Credentials.SessionToken <<< "$sts")"
  declare -p AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
}

if [[ "${BASH_SOURCE[0]}" == "${0}" ]] ; then
  set -e
  assume-role "$@"
fi