Last active
January 27, 2020 12:52
-
-
Save sgtoj/4fb6bf2bdb68b8992cdca54b82835faf to your computer and use it in GitHub Desktop.
Simple Script to Create MFA Login Sessions for AWS CLI and SDK
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 nameddefault-mfa
with session credentials.Instructions
boto3
awslogin.py
PROFILE_TO_MFA_SERIAL_MAP
Global Variable<ACCOUNT_NUMBER>
<IAM_USER>
python awslogin.py <profile-name> <mfa-token>
Suggestion (Linux)
~/bin
Directory~/bin
awslogin
without an extensionchmod 750 ~/bin/awslogin
~/bin/
toPATH
via~/.bashrc
source ~/.bashrc
awslogin <profile-name> <mfa-token>