Skip to content

Instantly share code, notes, and snippets.

@daxroc
Last active September 5, 2017 15:43
Show Gist options
  • Save daxroc/f5966c2a1b9ab1a042f5896c28df4edd to your computer and use it in GitHub Desktop.
Save daxroc/f5966c2a1b9ab1a042f5896c28df4edd to your computer and use it in GitHub Desktop.
AWS CLI Helper for switching shell variables on multiple profiles

AWS Command Line helper

Useful for manipulating Credentials generated using AWS CLI sts:assume role

Usage

This helper assumes you have configured aws-cli tool to handle multiple profiles and assumes that you have exported the profile you wish to use as the AWS_DEFAULT_PROFILE variable

export AWS_DEFAULT_PROFILE=Dev

Generating Credentials

aws ec2 describe-instances
# prompt for MFA token
# Command output ...

Export Credentials to shell

eval $(~/bin/env2.py --shell)

Unsetting Credentials

eval $(~/bin/env2.py --unset)

Enjoy!

#!/usr/bin/env python
import os
import json
import argparse
from pprint import pprint
from ConfigParser import SafeConfigParser
HOME = os.environ['HOME']
PROFILE = os.environ['AWS_DEFAULT_PROFILE']
#print PROFILE
parser = argparse.ArgumentParser(description='Short sample app')
parser.add_argument('--profile', action="store", default=PROFILE)
parser.add_argument('--shell', action="store_true", default=False)
parser.add_argument('--unset', action="store_true", default=False)
parser.add_argument('--tfvars', action="store_true", default=False)
parser.add_argument('--debug', action="store_true", default=False)
#parser.add_argument('-c', action="store", dest="c", type=int)
args = parser.parse_args()
cfgParser = SafeConfigParser()
cfgParser.read('{home}/.aws/config'.format(HOME))
if(args.debug):
print args
print cfgParser.sections()
arn = cfgParser.get("profile {}".format(args.profile), "role_arn").split(':')[4]
credentials = "{home}/.aws/cli/cache/{profile}--arn_aws_iam__{arn}_role-Administrator.json".format(home=HOME,arn=arn, profile=PROFILE)
with open(credentials) as data_file:
data = json.load(data_file)
if(args.debug):
pprint(data)
if(args.shell):
print """
export AWS_ACCESS_KEY_ID={Credentials[AccessKeyId]}
export AWS_SECRET_ACCESS_KEY={Credentials[SecretAccessKey]}
export AWS_SESSION_TOKEN={Credentials[SessionToken]}
""".format(**data).strip()
if(args.unset):
print """unset AWS_ACCESS_KEY_ID
unset AWS_SECRET_ACCESS_KEY
unset AWS_SESSION_TOKEN
"""
if(args.tfvars):
print """
aws_access_key = "{Credentials[AccessKeyId]}"
aws_secret_key = "{Credentials[SecretAccessKey]}"
aws_token = "{Credentials[SessionToken]}"
""".format(**data).strip()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment