Skip to content

Instantly share code, notes, and snippets.

@sgtoj
Last active January 27, 2020 12:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgtoj/4fb6bf2bdb68b8992cdca54b82835faf to your computer and use it in GitHub Desktop.
Save sgtoj/4fb6bf2bdb68b8992cdca54b82835faf to your computer and use it in GitHub Desktop.
Simple Script to Create MFA Login Sessions for AWS CLI and SDK
#!/usr/bin/env python3
import sys
from configparser import SafeConfigParser
from pathlib import Path
import boto3
import botocore
AWS_PROFILE_PATH = f"{Path.home()}/.aws/credentials"
AWS_DEFAULT_REGION = "us-east-1"
AWS_MFA_PROFILE_SUFFIX = "-mfa"
PROFILE_TO_MFA_SERIAL_MAP = {
"default": "arn:aws:iam::<ACCOUNT_NUMBER>:mfa/<IAM_USER>",
}
SESSION_DURATION = 43200 # 12hrs
def update_profile_config(profile, credentials):
mfa_profile = f"{profile}{AWS_MFA_PROFILE_SUFFIX}"
config = SafeConfigParser()
config.read(AWS_PROFILE_PATH)
if config.has_section(mfa_profile):
config.remove_section(mfa_profile)
config.add_section(mfa_profile)
config.set(mfa_profile, "region", AWS_DEFAULT_REGION)
config.set(mfa_profile, "aws_access_key_id", credentials["AccessKeyId"])
config.set(mfa_profile, "aws_secret_access_key ", credentials["SecretAccessKey"])
config.set(mfa_profile, "aws_session_token", credentials["SessionToken"])
with open(AWS_PROFILE_PATH, "w") as aws_creds_file:
config.write(aws_creds_file)
def get_session_token(profile, token):
session = boto3.Session(profile_name=profile)
sts = session.client("sts")
serial = PROFILE_TO_MFA_SERIAL_MAP[profile]
response = sts.get_session_token(SerialNumber=serial, TokenCode=token, DurationSeconds=SESSION_DURATION)
credentials = response["Credentials"]
return credentials
def create_mfa_session(profile, token):
credentials = get_session_token(profile, token)
update_profile_config(profile, credentials)
return credentials
def run_script(args):
try:
session = create_mfa_session(args[1], args[2])
print(f"AWS_ACCESS_KEY_ID={session['AccessKeyId']}")
print(f"AWS_SECRET_ACCESS_KEY={session['SecretAccessKey']}")
print(f"AWS_SESSION_TOKEN={session['SessionToken']}")
except botocore.exceptions.ClientError as error:
if error.response["Error"]["Code"] == "AccessDenied":
sys.exit(error.response["Error"]["Message"])
else:
raise error
if __name__ == "__main__":
run_script(sys.argv)
@sgtoj
Copy link
Author

sgtoj commented Aug 11, 2019

Normal MFA Login: https://aws.amazon.com/premiumsupport/knowledge-center/authenticate-mfa-cli/

This is an intentionally simple script to simplify creating MFA login sessions for AWS CLI and SDK. It will update the AWS profile file, under the user's home directory, by adding/updating a profile with MFA credentials. However, it does not modify the original profile. If the original profile name is default, it will create/update a profile named default-mfa with session credentials.

Instructions

  • Install Python 3
  • Install AWS Official Python SDK: boto3
  • Save this Script as awslogin.py
  • Edit the Script's PROFILE_TO_MFA_SERIAL_MAP Global Variable
    • Replace <ACCOUNT_NUMBER>
    • Replace <IAM_USER>
    • The template ARN is for only virtual MFA devices
  • Execute: python awslogin.py <profile-name> <mfa-token>
  • Profile is Ready to Use

Suggestion (Linux)

  • Create ~/bin Directory
  • Save script to ~/bin
  • Name script awslogin without an extension
  • Update its permissions: chmod 750 ~/bin/awslogin
  • Add ~/bin/ to PATH via ~/.bashrc
  • Reload the file: source ~/.bashrc
  • Ready to use via: awslogin <profile-name> <mfa-token>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment