Last active
October 28, 2021 04:50
-
-
Save davegallant/2c042686a78684a657fe99e20fa7a924 to your computer and use it in GitHub Desktop.
AWS Access Key Rotator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# | |
# This script will collect all existing access keys of the current caller identity, | |
# create a new access key, update your credentials file, and then delete all previously existing access keys. | |
# | |
# This only works if the caller identity is an IAM User because if you're using AWS SSO or temporary session credentials, | |
# you probably don't need this. | |
# | |
import argparse | |
import configparser | |
import os | |
from os.path import expanduser | |
import boto3 | |
AWS_SHARED_CREDENTIALS_FILE = os.getenv( | |
"AWS_SHARED_CREDENTIALS_FILE", os.path.join(expanduser("~"), ".aws", "credentials") | |
) | |
def load_config(config_path): | |
config = configparser.ConfigParser() | |
config.read(config_path) | |
return config | |
def update_credentials(config, access_key, secret_key, profile): | |
config.set(profile, "aws_access_key_id", access_key) | |
config.set(profile, "aws_secret_access_key", secret_key) | |
return config | |
def write_credentials_to_config(config, credentials_path): | |
with open(credentials_path, "w") as configfile: | |
config.write(configfile) | |
def main(): | |
parser = argparse.ArgumentParser(description="rotates your aws access keys") | |
parser.add_argument("-p", "--profile", help="The AWS profile to use", required=True) | |
args = parser.parse_args() | |
session = boto3.session.Session(profile_name=args.profile) | |
# Slice the ARN to determine the username | |
user_name = session.client("sts").get_caller_identity()["Arn"].split("/")[-1] | |
print(f"Rotating the access keys for {user_name}") | |
iam_client = session.client("iam") | |
existing_access_keys = iam_client.list_access_keys( | |
UserName=user_name, | |
)["AccessKeyMetadata"] | |
new_access_key = iam_client.create_access_key( | |
UserName=user_name, | |
)["AccessKey"] | |
config = load_config(AWS_SHARED_CREDENTIALS_FILE) | |
updated_config = update_credentials( | |
config, | |
new_access_key["AccessKeyId"], | |
new_access_key["SecretAccessKey"], | |
args.profile, | |
) | |
write_credentials_to_config(updated_config, AWS_SHARED_CREDENTIALS_FILE) | |
for access_key in existing_access_keys: | |
print(f"Deleting access key: {access_key['AccessKeyId']}") | |
iam_client.delete_access_key( | |
UserName=user_name, | |
AccessKeyId=access_key["AccessKeyId"], | |
) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment