Guest User

Untitled

a guest
Jul 18th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. import os
  3. import json
  4. import argparse
  5. import subprocess
  6. import configparser
  7.  
  8. parser = argparse.ArgumentParser(description='Rotate your AWS access key')
  9. parser.add_argument('user', help='AWS user name to rotate keys for')
  10. parser.add_argument('--credential-path', help='path to the aws credentials file', default=os.path.expanduser('~/.aws/credentials'))
  11.  
  12. args = parser.parse_args()
  13.  
  14. if args.user is None:
  15. parser.error('Expecting user name')
  16.  
  17. result = subprocess.run(['aws', 'iam', 'create-access-key', '--user-name', args.user], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  18. if result.returncode != 0:
  19. parser.error(result.stderr.decode('utf-8').strip('\n'))
  20.  
  21. credentials = json.loads(result.stdout.decode('utf-8'))['AccessKey']
  22.  
  23. config = configparser.ConfigParser()
  24. config.read(args.credential_path)
  25.  
  26. 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)
  27. if result.returncode != 0:
  28. parser.error(result.stderr.decode('utf-8').strip('\n'))
  29.  
  30. config['default']['aws_access_key_id'] = credentials['AccessKeyId']
  31. config['default']['aws_secret_access_key'] = credentials['SecretAccessKey']
  32.  
  33. with open(args.credential_path, 'w') as configFile:
  34. config.write(configFile)
  35.  
  36. print('Added new access key {}'.format(config['default']['aws_access_key_id']))
Add Comment
Please, Sign In to add comment