Skip to content

Instantly share code, notes, and snippets.

@mgmarino
Created June 15, 2017 10:59
Show Gist options
  • Save mgmarino/49a87c08eb3514ddd062664376b0ff44 to your computer and use it in GitHub Desktop.
Save mgmarino/49a87c08eb3514ddd062664376b0ff44 to your computer and use it in GitHub Desktop.
import configparser
import os
import boto3
import sys
def fail(msg):
print(msg)
sys.exit(1)
aws_profile = os.getenv("AWS_DEFAULT_PROFILE")
if not aws_profile:
fail("'AWS_DEFAULT_PROFILE' must be set")
def resetCredentials(credentialName, newCredentials):
config = configparser.ConfigParser()
credentials_file = os.path.expanduser("~/.aws/credentials")
if os.path.exists(credentials_file):
config.read(os.path.expanduser("~/.aws/credentials"))
config[credentialName] = {}
newCreds = config[credentialName]
newCreds["aws_access_key_id"] = newCredentials["AccessKeyId"]
newCreds["aws_secret_access_key"] = newCredentials["SecretAccessKey"]
newCreds["aws_session_token"] = newCredentials["SessionToken"]
with open(credentials_file, "w") as outfile:
config.write(outfile)
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')
credentials = client.assume_role(
RoleArn=role_arn,
RoleSessionName="TempBuildSession"
)
return credentials["Credentials"]
if __name__ == '__main__':
if len(sys.argv) != 2:
fail("""
Usage: {} [nameOfCredentialSection]
""".format(sys.argv[0]))
creds = getTemporaryCredentials()
resetCredentials(sys.argv[1], creds)
@mgmarino
Copy link
Author

Script to allow resetting (overwriting) relevant sections of the credentials file with temporary credentials from an STS::AssumeRole call. These credentials can then be used for other programs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment