Getting AWS STS Session Tokens for MFA with AWS CLI and kubectl for EKS automatically

I've been working on some projects which require MFA for all access, including for CLI access and things like using kubectl with Amazon EKS. One super-annoying aspect of requiring MFA for CLI operations is that every day or so, you have to update your STS access token—and also for that token to work you have to update an AWS profile's Access Key ID and Secret Access Key.

I had a little bash function that would allow me to input a token code from my MFA device and it would spit out the values to put into my .aws/credentials file, but it was still tiring copying and pasting three values every single morning.

So I wrote a neat little executable Ansible playbook which does everything for me:

To use it, you can download the contents of that file to /usr/local/bin/aws-sts-token, make the file executable (chmod +x /usr/local/bin/aws-sts-token), and run the command:

./aws-sts-token -e aws_userarn=ARN_FROM_IAM -e aws_profile=PROFILE -e aws_sts_profile=STS_PROFILE -e token_code=TOKEN

This assumes you have Ansible and the AWS CLI installed on your workstation. I wrapped the call to the executable in my original bash function so I can, once a day, run the following command to 'log in' via MFA to use AWS CLI and other applications which require a session token in the AWS profile:

awssts MFA_TOKEN_HERE

The bash function is:

# AWS STS Token.
function awssts() {
  if [[ ! "$1" ]] ; then
    echo "You must supply a token code."
    return 0
  fi

  aws-sts-token -e "aws_userarn=IAM_ARN_FOR_MFA" -e aws_profile="PROFILE_WITHOUT_TOKEN" -e aws_sts_profile="PROFILE_FOR_STS" -e token_code=$1
  return 0
}