Last active
May 21, 2025 16:58
-
-
Save roboticpuppies/c0078aea83866fda9488ed55d464fb1d to your computer and use it in GitHub Desktop.
aws alias generator
This file contains hidden or 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
| import boto3 | |
| import re | |
| # Clean instance name by removing non-alphanumeric characters | |
| # So if you have an instance named "AWS-Instance-(2)", it will be written as "AWSInstance2" | |
| def clean_name(name): | |
| return re.sub(r'[^a-zA-Z0-9]', '', name) | |
| # Get the instance list | |
| def get_ec2_instances(region): | |
| ec2_client = boto3.client('ec2', region_name=region) | |
| instances = [] | |
| try: | |
| # Call AWS EC2 API to get instance details | |
| # Only get running or stopped instances | |
| response = ec2_client.describe_instances( | |
| Filters=[ | |
| { | |
| "Name": "instance-state-name", | |
| "Values": ["stopped", "running"] | |
| } | |
| ] | |
| ) | |
| for reservation in response['Reservations']: | |
| for instance in reservation['Instances']: | |
| # Convert tag list into a dict and get the instance name in the "Name" tag. | |
| tags = {tag['Key']: tag['Value'] for tag in instance.get('Tags', [])} | |
| name = tags.get('Name') | |
| # If the "Name" tag is not empty | |
| if name is not None: | |
| # then clean and convert the instance name to lowercase | |
| name = clean_name(name).lower() | |
| # Get the private IP address of that instance (or 'N/A' if not available) | |
| # TODO: Add logic to determine which IP address I need to get if there is multiple network interfaces | |
| private_ip = instance.get('PrivateIpAddress', 'N/A') | |
| instances.append({'Name': name, 'PrivateIP': private_ip}) | |
| # Print error | |
| except Exception as e: | |
| print(f"Error: {e}") | |
| return instances | |
| if __name__ == "__main__": | |
| # Set the region of AWS for which you want to generate the alias | |
| region = "ap-southeast-3" | |
| # TODO: You might want to set this to your own username | |
| os_user = "ubuntu" | |
| ec2_instances = get_ec2_instances(region) | |
| for instance in ec2_instances: | |
| # Print out SSH alias for each instance | |
| print(f"alias {instance['Name']}=\"ssh {os_user}@{instance['PrivateIP']}\"") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment