Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/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']))
Add Comment
Please, Sign In to add comment