quickly rotate your aws access key
#!/usr/bin/env python3 | |
import boto3 | |
import os | |
import pprint | |
import sys | |
import termios | |
import tty | |
""" | |
run this to quickly rotate the currently active aws access key. | |
assumptions: | |
- you are using a credentials file, not environment variables for your access key | |
- the key you want to rotate is correctly stored in ~/.aws/credentials | |
- the key you want to rotate is the currently active key for boto3 | |
- there is only one access key for the current user | |
- any other files containing the access key are also in ~/.aws/* | |
""" | |
# define a quick get-single-key-press fn | |
def getch(): # from https://github.com/nathants/py-shell/blob/ab1f3b1acf629e08304b4ca997f906e715066f76/shell/__init__.py#L260 | |
fd = sys.stdin.fileno() | |
old = termios.tcgetattr(fd) | |
try: | |
tty.setraw(fd) | |
val = sys.stdin.read(1).lower() | |
if val == '\x03': | |
sys.exit(1) | |
else: | |
return val | |
except KeyboardInterrupt: | |
sys.exit(1) | |
finally: | |
termios.tcsetattr(fd, termios.TCSADRAIN, old) | |
# move to home dir | |
os.chdir(os.path.expanduser('~/')) | |
# read currently load creds | |
boto3.setup_default_session() | |
creds = boto3.DEFAULT_SESSION.get_credentials() | |
current_access_key = creds.access_key | |
current_secret_key = creds.secret_key | |
# make sure the creds live where we expect them to | |
try: | |
with open('.aws/credentials') as f: | |
text = f.read() | |
assert current_access_key in text | |
assert current_secret_key in text | |
except: | |
print('error: didnt find any instances of the current access key in ~/.aws/credentials:', current_access_key) | |
sys.exit(1) | |
# confirm account and user | |
ident = boto3.client('sts').get_caller_identity() | |
iam_user_name = ident['Arn'].split('/')[-1] | |
print('going to rotate the access key in:') | |
print(' aws account:', ident['Account']) | |
print(' iam user:', iam_user_name) | |
print(' access key:', current_access_key) | |
print('\nproceed? y/n') | |
assert getch() == 'y', 'aborting...' | |
# confirm that only one access key exists | |
iam = boto3.client('iam') | |
keys = iam.list_access_keys()['AccessKeyMetadata'] | |
if len(keys) != 1: | |
print('error: there is more than 1 key, aborting...') | |
pprint.pprint(keys) | |
sys.exit(1) | |
# create a new access key | |
new_key = iam.create_access_key(UserName=iam_user_name)['AccessKey'] | |
print('created a new access key pair') | |
# update the access key pair everywhere it is found in ~/.aws/* | |
for path in os.listdir('.aws'): | |
path = f'.aws/{path}' | |
if os.path.isfile(path): | |
with open(path) as f: | |
orig_text = text = f.read() | |
text = text.replace(current_access_key, new_key['AccessKeyId']) | |
text = text.replace(current_secret_key, new_key['SecretAccessKey']) | |
if text != orig_text: | |
with open(path, 'w') as f: | |
f.write(text) | |
print('updated:', path) | |
# delete the old access key | |
iam.delete_access_key(UserName=iam_user_name, AccessKeyId=current_access_key) | |
print('deleted the old access key pair') | |
# print the old and new access key id | |
boto3.DEFAULT_SESSION = None | |
boto3.setup_default_session() | |
new_access_key = boto3.DEFAULT_SESSION.get_credentials().access_key | |
print('rotated access keys:', current_access_key, '->', new_access_key) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment