Last active
July 18, 2018 16:01
-
-
Save drvdana/c94e7e5d361a854be5c1618226520742 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
#!/usr/bin/env python3 | |
import os | |
import json | |
import argparse | |
import subprocess | |
import configparser | |
parser = argparse.ArgumentParser(description='Rotate your AWS access key') | |
parser.add_argument('user', help='AWS user name to rotate keys for') | |
parser.add_argument('--credential-path', help='path to the aws credentials file', default=os.path.expanduser('~/.aws/credentials')) | |
args = parser.parse_args() | |
if args.user is None: | |
parser.error('Expecting user name') | |
result = subprocess.run(['aws', 'iam', 'create-access-key', '--user-name', args.user], stdout=subprocess.PIPE, stderr=subprocess.PIPE) | |
if result.returncode != 0: | |
parser.error(result.stderr.decode('utf-8').strip('\n')) | |
credentials = json.loads(result.stdout.decode('utf-8'))['AccessKey'] | |
config = configparser.ConfigParser() | |
config.read(args.credential_path) | |
result = subprocess.run(['aws', 'iam', 'delete-access-key', '--access-key-id', config['default']['aws_access_key_id'], '--user-name', args.user], stdout=subprocess.PIPE, stderr=subprocess.PIPE) | |
if result.returncode != 0: | |
parser.error(result.stderr.decode('utf-8').strip('\n')) | |
config['default']['aws_access_key_id'] = credentials['AccessKeyId'] | |
config['default']['aws_secret_access_key'] = credentials['SecretAccessKey'] | |
with open(args.credential_path, 'w') as configFile: | |
config.write(configFile) | |
print('Added new access key {}'.format(config['default']['aws_access_key_id'])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This will rotate your AWS IAM Access Keys, updating your ~/.aws/credentials file for you.
This assumes you have one access key, that was previously setup using this script or
aws configure
.