Last active
December 7, 2018 01:04
-
-
Save gergnz/94b9ec093277b223114178400ea9db17 to your computer and use it in GitHub Desktop.
export_aws_credetials_from_config
This file contains hidden or 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 boto3 | |
import configparser | |
import logging | |
import os | |
import sys | |
import pprint | |
LOG = logging.getLogger() | |
LOG.setLevel(logging.DEBUG) | |
AWS_PROFILE = os.getenv('AWS_PROFILE') | |
AWS_CONFIG_PROFILE = 'profile ' + AWS_PROFILE | |
HOME = os.getenv('HOME') | |
if AWS_PROFILE is None: | |
LOG.error('Please set AWS_PROFILE') | |
sys.exit(1) | |
credentials = configparser.ConfigParser() | |
config = configparser.ConfigParser() | |
credentials.read(HOME + '/.aws/credentials') | |
config.read(HOME + '/.aws/config') | |
if AWS_PROFILE in credentials: | |
for key in credentials[AWS_PROFILE]: | |
if key.startswith('aws_'): | |
print("export %s=%s" % (key.upper(), credentials[AWS_PROFILE][key])) | |
sys.exit() | |
if AWS_CONFIG_PROFILE in config: | |
if config[AWS_CONFIG_PROFILE]['source_profile'] not in credentials: | |
LOG.error("couldn't find source_profile in aws credetails") | |
sys.exit(1) | |
try: | |
sts = boto3.client('sts', | |
aws_access_key_id=credentials[config[AWS_CONFIG_PROFILE]['source_profile']]['aws_access_key_id'], | |
aws_secret_access_key=credentials[config[AWS_CONFIG_PROFILE]['source_profile']]['aws_secret_access_key'], | |
aws_session_token=credentials[config[AWS_CONFIG_PROFILE]['source_profile']]['aws_session_token'] | |
) | |
response = sts.assume_role( | |
RoleArn=config[AWS_CONFIG_PROFILE]['role_arn'], | |
RoleSessionName='madeup' | |
) | |
except: | |
LOG.error("Unexpected error:", sys.exc_info()[0]) | |
sys.exit(1) | |
print("export AWS_ACCESS_KEY_ID=%s" % response['Credentials']['AccessKeyId']) | |
print("export AWS_SECRET_ACCESS_KEY=%s"% response['Credentials']['SecretAccessKey']) | |
print("export AWS_SESSION_TOKEN=%s" % response['Credentials']['SessionToken']) | |
print("export AWS_SECURITY_TOKEN=%s" % response['Credentials']['SessionToken']) | |
sys.exit() | |
# else explode as we couldn't find anything | |
LOG.error('unable to find profile %s in aws credentials or config' % AWS_PROFILE) | |
sys.exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment