Skip to content

Instantly share code, notes, and snippets.

@toshke
Last active July 6, 2021 00:27
Show Gist options
  • Save toshke/6ae81c05b3e0fc84acef1d15c30407b8 to your computer and use it in GitHub Desktop.
Save toshke/6ae81c05b3e0fc84acef1d15c30407b8 to your computer and use it in GitHub Desktop.
Rotate AWS access keys for a profile python script
#!/usr/bin/env python3
import sys
import os
import boto3
import shlex
def rotate(profile: str):
sts = boto3.client('sts')
iam = boto3.client('iam')
user_arn = sts.get_caller_identity()['Arn']
user = user_arn.split(':')[5].split('/')[1]
keys = iam.list_access_keys(UserName=user)['AccessKeyMetadata']
if len(keys) == 0:
raise f"No access keys for {profile}"
if len(keys) > 1:
raise f"More than one key for {profile}"
print(f'Old key: {keys[0]}\n\nGenerating new key..')
new_key = iam.create_access_key(UserName=user)
new_id = new_key['AccessKey']['AccessKeyId']
new_secret = new_key['AccessKey']['SecretAccessKey']
cmd=f"aws configure set --profile {shlex.quote(profile)} aws_access_key_id {new_id}"
# print(cmd)
os.system(cmd)
cmd=f"aws configure set --profile {shlex.quote(profile)} aws_secret_access_key {new_secret}"
# print(cmd)
os.system(cmd)
old_key_id = keys[0]["AccessKeyId"]
print(f"Remove old key {old_key_id}")
iam.delete_access_key(UserName=user, AccessKeyId=old_key_id)
print(f"Use \"aws iam list-access-keys --user {user} --profile {profile}\" for new key")
if __name__ == '__main__':
profile = sys.argv[1]
os.environ['AWS_PROFILE'] = profile
rotate(profile)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment