Skip to main content
100%

Gist df3a4c8340b0fc248e44e04b3a194f60

✓ Published0🌍 Public
Aaharonh
Last edited Oct 1, 2021
Created on Oct 1, 2021

This script automates the renewal of temporary AWS credentials required when MFA is enabled for AWS CLI authentication. It shows the process of exchanging a one-time MFA token for session credentials by calling the AWS STS `get-session-token` API via the `aws` command-line tool. The code uses Python’s `subprocess.run`, `json.loads`, and `configparser` to parse the command output and update the specified `~/.aws/credentials` file with new access key, secret key, and session token. It takes five command-line arguments—start profile, MFA profile, credentials filename, MFA device ARN, and token—and writes the refreshed credentials to the designated profile section.

AI-generated description

this script automates the required update of temporary access credentials required when MFA is configured for aws cli authentication. it is meant to be run each time (cca once a day) the temporary tokens expired so it will renew them. it was tested on both linux and windows with python3. below is a short explanation on how to use.

let's assume you there is an aws profile named 'root' configured for access and you have enabled MFA for aws cli. Then you should add profile called root-mfa in both ~/.aws/config and ~/.aws/credentials as follows:

config

[profile root-mfa]
region = us-east-1
output = json

credentials

[root-mfa]
aws_access_key_id = a
aws_secret_access_key = a
aws_session_token = a

the credentials file root-mfa section will be updated by the script when it is run and supplied valid one-time access token.

place the script aws-mfa-login.py into ~/bin/ or other folder in path, set the current aws profile to root and run

AWS_PROFILE=root; aws-mfa-login.py root root-mfa ~/.aws/credentials arn:aws:iam::137602392568:mfa/aharon.haravon 647239

the parameters are respectively:

  • start aws profile
  • mfa aws profile
  • credentials filename
  • mfa device arn
  • current mfa token token value

now you can use the root-mfa aws profile

Similar vizzes