Last active
December 2, 2020 21:24
-
-
Save xlbruce/c5a29e49f5c34023779b5f4d6a1ce96b to your computer and use it in GitHub Desktop.
This script can be used in a EC2 instance to assume a role that lives in another account. IAM permissions must be set before use this.
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 python | |
# Intended to be used with Python 2.7.5 | |
import json | |
import subprocess | |
import shlex | |
import sys | |
import os | |
import logging | |
import logging.handlers | |
log = None | |
app_name = os.path.basename(sys.argv[0]) | |
role_arn = "arn:aws:iam::ACCOUNT_ID:role/ROLE_NAME" | |
def setup_log(): | |
global log | |
global app_name | |
log = logging.getLogger(__name__) | |
log.setLevel(logging.INFO) | |
handler = logging.handlers.SysLogHandler(address = '/dev/log') | |
formatter = logging.Formatter('{app_name}: %(message)s'.format(app_name=app_name)) | |
handler.setFormatter(formatter) | |
log.addHandler(handler) | |
setup_log() | |
log.info('Generating new AWS temporary credentials') | |
''' | |
Workaround to assume "role_arn" in order access resources from that account. | |
This script will assume the cross account role and will write the temporary credentials in $HOME/.aws/credentials | |
''' | |
home_dir = os.path.expanduser('~') | |
aws_dir = '{}/.aws'.format(home_dir) | |
credentials_file = "{}/credentials".format(aws_dir) | |
if not os.path.exists(aws_dir): | |
log.info('Creating .aws directory') | |
subprocess.Popen(shlex.split('/bin/mkdir {}'.format(aws_dir))) | |
'''Credentials file must be emptied to assume the correct instance profile''' | |
log.info('Truncating {}'.format(credentials_file)) | |
with open(credentials_file, 'w') as f: | |
f.write('') | |
f.flush() | |
log.info("Assuming cross account role: {}".format(role_arn)) | |
assume_role_cmd = "/bin/aws sts assume-role --role-arn {role_arn} --role-session-name cross-role".format(role_arn=role_arn) | |
cmd = shlex.split(assume_role_cmd) | |
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) | |
stdout, stderr = proc.communicate() | |
try: | |
parsed = json.loads(stdout) | |
except: | |
log.error("Something went wrong with AWS credentials: \n{}".format(stdout)) | |
log.error("Stderr is:\n{}".format(sterr)) | |
sys.exit(1) | |
try: | |
credentials = parsed['Credentials'] | |
except: | |
log.error("Can't get credentials: \n{}".format(parsed)) | |
sys.exit(1) | |
credentials_aws = '''# Generated by {app_name} | |
[default] | |
aws_secret_access_key={secret_key} | |
aws_access_key_id={access_key} | |
aws_session_token={session_token} | |
'''.format(app_name=app_name, | |
secret_key=credentials['SecretAccessKey'], | |
access_key=credentials['AccessKeyId'], | |
session_token=credentials['SessionToken']) | |
credentials_file = "{}/credentials".format(aws_dir) | |
log.info("Saving temporary credentials to {}".format(credentials_file)) | |
with open(credentials_file, 'w') as f: | |
f.write(credentials_aws) | |
f.flush() | |
log.info('All done') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment