Skip to content

Instantly share code, notes, and snippets.

@garyellis
Created January 5, 2018 02:01
Show Gist options
  • Save garyellis/b666d0ef0fac79ddf4a168b1269e0395 to your computer and use it in GitHub Desktop.
Save garyellis/b666d0ef0fac79ddf4a168b1269e0395 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""
A quick script to get temporary aws access keys.
expects AWS_MFA_ARN to exist in the aws default credential
export AWS_MFA_ARN="arn:aws:iam::123456789:mfa/me"
"""
import boto3
import ConfigParser
import getpass
from pprint import pprint
import os
from os.path import expanduser
if os.environ['AWS_MFA_ARN']:
serial_arn = os.environ['AWS_MFA_ARN']
else:
serial_arn = input('serial arn: ')
mfa_token = getpass.getpass(prompt="mfa token: ")
client = boto3.client('sts')
response = client.get_session_token(
SerialNumber=serial_arn,
TokenCode=mfa_token
)
temporary_credentials = response.get('Credentials', {})
config = ConfigParser.RawConfigParser()
awscredentialfilename = '.aws/credentials'
awscredentialfile = '%s/%s' % (expanduser("~"), awscredentialfilename)
config_section_name = 'authenticated'
config = ConfigParser.RawConfigParser()
config.read(awscredentialfile)
if not config.has_section(config_section_name):
config.add_section(config_section_name)
config.set(config_section_name, 'region', 'us-west-2')
config.set(config_section_name, 'aws_access_key_id', temporary_credentials['AccessKeyId'])
config.set(config_section_name, 'aws_secret_access_key', temporary_credentials['SecretAccessKey'])
config.set(config_section_name, 'aws_session_token', temporary_credentials['SessionToken'])
with open(awscredentialfile, 'wb') as f:
config.write(f)
print '==> Temporary credentials have been created.'
print ' CredentialFile: %s' % awscredentialfile
print ' AwsProfile: %s' % config_section_name
print ' AccessKeyId: %s' % temporary_credentials['AccessKeyId']
print ' Expiration: %s' % temporary_credentials['Expiration']
print ' Export: export AWS_DEFAULT_PROFILE=%s AWS_PROFILE=%s' % (config_section_name,config_section_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment