From 72218cb99e96c226644c3effe365a45bea4a76e5 Mon Sep 17 00:00:00 2001 From: Yury Hrytsuk <50014626+YuryHrytsuk@users.noreply.github.com> Date: Tue, 14 Nov 2023 16:05:11 +0100 Subject: [PATCH] Add helpers folder (#437) * Return removed staging CA for letsenrypt * Fix missing $ * Remove PAYMENTS_AUTORECHARGE_DEFAULT_MIN_BALANCE * Add helpers scripts --- scripts/helpers/gen_pwd.py | 19 ++++++++++ scripts/helpers/get_unused_aws_key_pairs.py | 41 +++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 scripts/helpers/gen_pwd.py create mode 100644 scripts/helpers/get_unused_aws_key_pairs.py diff --git a/scripts/helpers/gen_pwd.py b/scripts/helpers/gen_pwd.py new file mode 100644 index 00000000..b9f6aca3 --- /dev/null +++ b/scripts/helpers/gen_pwd.py @@ -0,0 +1,19 @@ +import secrets +import string +import sys + + +def generate_password(length=12): + # https://stackoverflow.com/a/39596292 + alphabet = string.ascii_letters + string.digits + password = "".join(secrets.choice(alphabet) for i in range(length)) + return password + + +if len(sys.argv) < 2: + pwd_len = 30 +else: + pwd_len = int(sys.argv[1]) + +new_password = generate_password(pwd_len) +print(new_password) diff --git a/scripts/helpers/get_unused_aws_key_pairs.py b/scripts/helpers/get_unused_aws_key_pairs.py new file mode 100644 index 00000000..a48ee8a3 --- /dev/null +++ b/scripts/helpers/get_unused_aws_key_pairs.py @@ -0,0 +1,41 @@ +import sys +from pprint import pprint + +import boto3 + +# Create a session with the specified profile or use the default profile +profile_name = sys.argv[1] if len(sys.argv) > 1 else None +session = boto3.Session(profile_name=profile_name) + +# Use the session to create an EC2 client to get the default region +ec2_client = session.client("ec2") +default_region = ec2_client.meta.region_name + +# Use the session to create an EC2 resource with the default region +ec2 = session.resource("ec2", region_name=default_region) + +unused_keys = {} + +# Iterate over all regions +for region in ec2.meta.client.describe_regions()["Regions"]: + region_name = region["RegionName"] + try: + # Use the session to create an EC2 resource for the specific region + ec2conn = session.resource("ec2", region_name=region_name) + + # Get all key pairs in the region + key_pairs = ec2conn.key_pairs.all() + + # Get the names of key pairs used by instances in the region + used_keys = {instance.key_name for instance in ec2conn.instances.all()} + + # Iterate over key pairs and delete unused ones + for key_pair in key_pairs: + if key_pair.name not in used_keys: + unused_keys[key_pair.name] = region_name + except Exception as e: + print(f"No access to region {region_name}: {e}") + +# Print the results +print(f"Found {len(unused_keys)} unused key pairs across all regions:") +pprint(unused_keys)