Skip to content

Instantly share code, notes, and snippets.

@john-auld
Last active July 27, 2019 15:57
Show Gist options
  • Save john-auld/2c587b6c1530f4248599271416fdc4fd to your computer and use it in GitHub Desktop.
Save john-auld/2c587b6c1530f4248599271416fdc4fd to your computer and use it in GitHub Desktop.
Python 3 compatible script to rotate aws access keys
'''
Rotate AWS access keys for each profile in the users ${HOME}/.aws/credentials file.
Note: the default profile is not altered
Author: John Auld
'''
import configparser
import os
import boto3
aws_credentials_file = str.join('\\', (os.path.expanduser('~\\.aws'), 'credentials'))
config = configparser.ConfigParser()
config.read(aws_credentials_file)
for aws_account in config.sections():
if (aws_account != 'default'):
print("Rotating access key for: %s" % aws_account)
old_key = config[aws_account]['aws_access_key_id']
old_secret = config[aws_account]['aws_secret_access_key']
sts_client = boto3.client(
'sts',
aws_access_key_id = old_key,
aws_secret_access_key = old_secret,
)
iam_client = boto3.client(
'iam',
aws_access_key_id = old_key,
aws_secret_access_key = old_secret,
)
caller_identity = sts_client.get_caller_identity()
aws_user = caller_identity['Arn'].split('/')[1]
response = iam_client.create_access_key(
UserName = aws_user,
)
config[aws_account]['aws_access_key_id'] = response['AccessKey']['AccessKeyId']
config[aws_account]['aws_secret_access_key'] = response['AccessKey']['SecretAccessKey']
with open(aws_credentials_file, 'w') as configfile:
config.write(configfile)
iam_client.delete_access_key(
AccessKeyId = old_key,
UserName = aws_user,
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment