Created
November 17, 2015 18:17
-
-
Save Raniz85/4eb10b1908511e8bc569 to your computer and use it in GitHub Desktop.
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 | |
# -*- encoding: utf8 -*- | |
import sys | |
try: | |
import boto3 | |
import tzlocal | |
except ImportError: | |
print("This script requires boto3 and tzlocal. Please make sure both are installed") | |
print("Python ", end="") | |
print(sys.version) | |
sys.exit(1) | |
import argparse | |
import configparser | |
import getpass | |
import io | |
import os | |
import pytz | |
import time | |
parser = argparse.ArgumentParser(description = "Fetch credentials using AWS STS from a different account and store them in a profile.") | |
parser.add_argument("-p", "--profile", dest="profile", help="Profile name to use for the call to STS") | |
parser.add_argument("role", help="Profile name to store the assumed credentials in") | |
parser.add_argument("destination", help="Profile name to store the assumed credentials in") | |
args = parser.parse_args() | |
user = getpass.getuser() | |
now = int(time.time()) | |
session_name = "{}-{}".format(user[0:17], now) | |
sts = boto3.client('sts') | |
response = sts.assume_role(RoleArn = args.role, RoleSessionName = session_name) | |
credentials = response["Credentials"] | |
aws_credentials = configparser.ConfigParser() | |
credentials_file = os.path.expanduser("~/.aws/credentials") | |
if os.path.exists(credentials_file): | |
aws_credentials.read(credentials_file) | |
aws_credentials[args.destination] = { | |
"aws_access_key_id": credentials["AccessKeyId"], | |
"aws_secret_access_key": credentials["SecretAccessKey"], | |
"aws_session_token": credentials["SessionToken"] | |
} | |
with open(credentials_file, "w") as f: | |
aws_credentials.write(f) | |
print("Wrote credentials for profile {} to {}\n".format(args.destination, credentials_file)) | |
with open(credentials_file) as f: | |
print(f.read(), end="") | |
local_tz = tzlocal.get_localzone() | |
#expires = local_tz.localize(credentials['Expiration']) | |
expires = credentials['Expiration'].astimezone(local_tz) | |
print("\nCredentials will expire {}".format(expires.isoformat())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment