Last active
June 23, 2017 08:38
-
-
Save mgmarino/6be2fdcd771edeab0a987b3fe27c6daa to your computer and use it in GitHub Desktop.
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
import configparser | |
import os | |
import boto3 | |
import sys | |
import random | |
import string | |
def fail(msg): | |
sys.stderr.write("{}\n".format(msg)) | |
sys.exit(1) | |
aws_profile = os.getenv("AWS_DEFAULT_PROFILE") | |
for x in ["AWS_ACCESS_KEY_ID", "AWS_SESSION_TOKEN", "AWS_SECRET_ACCESS_KEY"]: | |
if x in os.environ: | |
os.environ.pop(x) | |
if not aws_profile: | |
fail("'AWS_DEFAULT_PROFILE' must be set") | |
def getTemporaryCredentials(): | |
config = configparser.ConfigParser() | |
config.read(os.path.expanduser("~/.aws/config")) | |
profile = config["profile {}".format(aws_profile)] | |
role_arn = profile["role_arn"] | |
client = boto3.client('sts') | |
random_postfix = ''.join(random.choice(string.ascii_uppercase + | |
string.digits) for _ in range(6)) | |
credentials = client.assume_role( | |
RoleArn=role_arn, | |
RoleSessionName="TempBuildSession{}".format(random_postfix) | |
) | |
return credentials["Credentials"] | |
def printTemporaryCredentials(credentials): | |
print(""" | |
export AWS_ACCESS_KEY_ID={AccessKeyId} | |
export AWS_SECRET_ACCESS_KEY={SecretAccessKey} | |
export AWS_SESSION_TOKEN={SessionToken} | |
""".format(**credentials)) | |
if __name__ == '__main__': | |
creds = getTemporaryCredentials() | |
printTemporaryCredentials(creds) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Call like: