Created
July 7, 2017 09:58
-
-
Save steynovich/a56b33ff16bab6ab19236e0038f2a637 to your computer and use it in GitHub Desktop.
Write AWS env credentials to credentials file in .aws
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
#!/usr/bin/env python | |
from __future__ import print_function | |
import ConfigParser | |
import os | |
import sys | |
try: | |
PROFILE = sys.argv[1] | |
except IndexError: | |
print('Usage: {} <profile_name>'.format(__file__)) | |
sys.exit(1) | |
CONFIG_FILE = os.path.expanduser('~/.aws/credentials') | |
def read_profile(settings): | |
""" | |
Read the configuration file | |
""" | |
settings.read(CONFIG_FILE) | |
return settings | |
def update_profile(settings): | |
""" | |
Update the stored profile with current credentials | |
""" | |
profile_name = PROFILE | |
if profile_name not in settings.sections(): | |
settings.add_section(profile_name) | |
try: | |
access_key_id = os.environ['AWS_ACCESS_KEY_ID'] | |
secret_access_key = os.environ['AWS_SECRET_ACCESS_KEY'] | |
session_token = os.environ['AWS_SESSION_TOKEN'] | |
except KeyError: | |
print('AWS credentials not found in env') | |
sys.exit(1) | |
settings.set(profile_name, 'output', 'json') | |
settings.set(profile_name, 'region', 'eu-west-1') | |
settings.set(profile_name, 'aws_access_key_id', access_key_id) | |
settings.set(profile_name, 'aws_secret_access_key', secret_access_key) | |
settings.set(profile_name, 'aws_session_token', session_token) | |
settings.set(profile_name, 'aws_security_token', session_token) | |
return settings | |
def write_profile(settings): | |
""" | |
Save new config file | |
""" | |
with open(CONFIG_FILE, 'w') as configfile: | |
settings.write(configfile) | |
return True | |
def main(): | |
parser = ConfigParser.ConfigParser() | |
parser = read_profile(parser) | |
parser = update_profile(parser) | |
process_name = os.path.basename(__file__) | |
if write_profile(parser): | |
print('{} - Credentials updated'.format(process_name)) | |
else: | |
print('{} - Failed'.format(process_name)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment