Below is a Python script using aioboto3 (the asynchronous version of boto3) to handle creating and deleting bastion hosts (EC2 instances) in multiple AWS regions. This script assumes:
- Bastion Host: A simple EC2 instance (e.g., t2.micro with the latest Amazon Linux 2 AMI) launched in a default VPC with a basic security group allowing SSH (port 22) from anywhere. In a real-world scenario, you'd customize this (e.g., use a specific VPC, subnet, key pair, and tighter security rules). You can modify the
create_bastion function accordingly.
- Regions: You provide a list of AWS regions (e.g., ['us-east-1', 'us-west-2']).
- Async Handling: Uses
asyncio and asyncio.gather for concurrent operations across regions.
- Deletion: Requires instance IDs (which you get from creation). It terminates the instances.
- Prerequisites:
- Install
aioboto3 via pip install aioboto3.
- Configure AWS credentials (e.g., via
~/.aws/credentials or environment variables).
- This is for demonstration; add error handling, logging, and IAM permissions as needed (e.g., EC2 full access).
- Limitations: AMI IDs are region-specific; the script uses a helper to fetch the latest Amazon Linux 2 AMI per region. No key pair is specified (instances won't be SSH-accessible without one—add
KeyName in production).
Script: aws_bastion_manager.py
import asyncio
import aioboto3
from botocore.exceptions import ClientError
async def get_latest_ami(region):
"""
Fetch the latest Amazon Linux 2 AMI ID for the given region.
"""
session = aioboto3.Session()
async with session.client('ssm', region_name=region) as ssm:
response = await ssm.get_parameters(
Names=['/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2']
)
return response['Parameters'][0]['Value']
async def create_bastion(region, instance_type='t2.micro', tag_name='BastionHost'):
"""
Create a bastion EC2 instance in the specified region.
Returns the instance ID if successful.
"""
session = aioboto3.Session()
async with session.client('ec2', region_name=region) as ec2:
try:
# Fetch latest AMI
ami_id = await get_latest_ami(region)
# Create a basic security group (allow SSH from anywhere - customize in prod)
sg_response = await ec2.create_security_group(
GroupName='bastion-sg',
Description='Security group for bastion host'
)
sg_id = sg_response['GroupId']
await ec2.authorize_security_group_ingress(
GroupId=sg_id,
IpPermissions=[
{'IpProtocol': 'tcp', 'FromPort': 22, 'ToPort': 22, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}
]
)
# Launch instance (add KeyName for SSH access in prod)
response = await ec2.run_instances(
ImageId=ami_id,
InstanceType=instance_type,
MinCount=1,
MaxCount=1,
SecurityGroupIds=[sg_id],
TagSpecifications=[{
'ResourceType': 'instance',
'Tags': [{'Key': 'Name', 'Value': tag_name}]
}]
)
instance_id = response['Instances'][0]['InstanceId']
print(f"Created bastion {instance_id} in {region}")
return instance_id
except ClientError as e:
print(f"Error creating bastion in {region}: {e}")
return None
async def delete_bastion(instance_id, region):
"""
Delete (terminate) a bastion EC2 instance in the specified region.
"""
session = aioboto3.Session()
async with session.client('ec2', region_name=region) as ec2:
try:
await ec2.terminate_instances(InstanceIds=[instance_id])
print(f"Terminated bastion {instance_id} in {region}")
except ClientError as e:
print(f"Error terminating bastion {instance_id} in {region}: {e}")
async def create_bastions_in_regions(regions):
"""
Create bastions concurrently in multiple regions.
Returns a list of (region, instance_id) tuples.
"""
tasks = [create_bastion(region) for region in regions]
instance_ids = await asyncio.gather(*tasks)
return [(regions[i], instance_ids[i]) for i in range(len(regions)) if instance_ids[i]]
async def delete_bastions_in_regions(region_instance_pairs):
"""
Delete bastions concurrently from multiple regions.
Expects a list of (region, instance_id) tuples.
"""
tasks = [delete_bastion(instance_id, region) for region, instance_id in region_instance_pairs]
await asyncio.gather(*tasks)
# Example usage
async def main():
regions = ['us-east-1', 'us-west-2'] # Add your regions here
# Create bastions
created = await create_bastions_in_regions(regions)
print("Created instances:", created)
# Delete bastions (using the created instance IDs)
await delete_bastions_in_regions(created)
if __name__ == "__main__":
asyncio.run(main())
How to Run
- Save the script as
aws_bastion_manager.py.
- Run it:
python aws_bastion_manager.py.
- It will create bastions in the specified regions, print their instance IDs, and then immediately delete them.
Explanation
- Creation:
- Fetches the latest AMI using SSM Parameter Store (async).
- Creates a security group and launches a t2.micro instance.
- Uses
asyncio.gather for concurrent creation across regions.
- Deletion:
- Terminates instances using their IDs.
- Also concurrent via
asyncio.gather.
- Customization:
- Add parameters like
KeyName, SubnetId, or custom AMIs.
- For production, handle waiting for instance readiness (e.g., use
wait_until_running).
- Error handling is basic; expand with retries or logging.
- Security Note: The security group allows SSH from 0.0.0.0/0—restrict this in real use (e.g., to your IP).
If you need more features (e.g., listing bastions, custom configs, or integration with other AWS services), let me know!