Skip to content

Instantly share code, notes, and snippets.

@brandongalbraith
Forked from rectalogic/aws_mfa.py
Created January 25, 2019 00:25
Show Gist options
  • Save brandongalbraith/67e69b5049d918132645af4b992518b7 to your computer and use it in GitHub Desktop.
Save brandongalbraith/67e69b5049d918132645af4b992518b7 to your computer and use it in GitHub Desktop.
import os
import getpass
import boto3
os.environ['AWS_ACCESS_KEY_ID'] = ... # your accounts access key
os.environ['AWS_SECRET_ACCESS_KEY'] = ... # your accounts secret
client = boto3.client("sts")
token = getpass.getpass("Enter MFA token -> ")
# Exchange permanent key/secret for temporary ones
response = client.get_session_token(
SerialNumber="arn:aws:iam::XXX:mfa/XXX", # your accounts ARN
TokenCode=token,
)
# response contains temporary access key and secret and session token
os.environ.update({
"AWS_ACCESS_KEY_ID": response["Credentials"]["AccessKeyId"],
"AWS_SECRET_ACCESS_KEY": response["Credentials"]["SecretAccessKey"],
"AWS_SECURITY_TOKEN": response["Credentials"]["SessionToken"],
})
# exec some CLI command with the above environment
os.execlp(command, command)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment