#!/usr/bin/env python3
"""
Sherlock's AWS Resource Provisioning Script
==========================================
This Python script uses Boto3 to automate the provisioning of an EC2 instance in AWS.
It performs the following steps:
1. Creates a new Security Group (if it doesn't exist) with inbound SSH access (port 22).
2. Launches an EC2 instance using the provided AMI, instance type, and key pair.
3. Waits for the instance to reach the 'running' state.
4. Outputs the instance ID, public IP, and public DNS name.
Prerequisites:
- AWS credentials configured (e.g., via `aws configure`, environment variables, or IAM roles).
- Valid AMI ID (e.g., Amazon Linux 2: ami-0abcdef1234567890 - check your region).
- Existing EC2 Key Pair name.
- Permissions: EC2 full access (or equivalent for describe, create, authorize_security_group_ingress).
Usage:
python provision_ec2.py --region us-east-1 --ami-id ami-0abcdef1234567890 \
--instance-type t3.micro --key-name my-key-pair \
--security-group-name my-sg --min-count 1 --max-count 1
Customization:
- Modify the Security Group rules as needed.
- Add tags via the --tags argument (JSON format: '{"Key1": "Value1"}').
Trailblazer Labs - Sherlock AI
"""
import argparse
import json
import sys
import boto3
from botocore.exceptions import ClientError, NoCredentialsError
def create_security_group(ec2_client, sg_name, vpc_id=None):
"""Create a Security Group if it doesn't exist."""
try:
# Check if SG exists
response = ec2_client.describe_security_groups(GroupNames=[sg_name])
print(f"Security Group '{sg_name}' already exists: {response['SecurityGroups'][0]['GroupId']}")
return response['SecurityGroups'][0]['GroupId']
except ClientError as e:
if e.response['Error']['Code'] == 'InvalidGroup.NotFound':
# Create new SG
sg_params = {
'GroupName': sg_name,
'Description': 'Automated SG for SSH access',
'GroupDescription': 'Allow SSH inbound'
}
if vpc_id:
sg_params['VpcId'] = vpc_id
sg = ec2_client.create_security_group(**sg_params)
sg_id = sg['GroupId']
# Authorize SSH inbound (IPv4)
ec2_client.authorize_security_group_ingress(
GroupId=sg_id,
IpPermissions=[
{
'IpProtocol': 'tcp',
'FromPort': 22,
'ToPort': 22,
'IpRanges': [{'CidrIp': '0.0.0.0/0'}] # Restrict to your IP in production!
}
]
)
print(f"Created Security Group '{sg_name}': {sg_id}")
return sg_id
raise e
def launch_ec2_instance(ec2_client, args):
"""Launch EC2 instance(s)."""
# Get default VPC ID if not specified
if not args.subnet_id:
vpcs = ec2_client.describe_vpcs(Filters=[{'Name': 'is-default', 'Values': ['true']}])
vpc_id = vpcs['Vpcs'][0]['VpcId'] if vpcs['Vpcs'] else None
else:
vpc_id = None # Subnet implies VPC
# Create or get Security Group
sg_id = create_security_group(ec2_client, args.security_group_name, vpc_id)
# Launch parameters
launch_params = {
'ImageId': args.ami_id,
'InstanceType': args.instance_type,
'MinCount': args.min_count,
'MaxCount': args.max_count,
'KeyName': args.key_name,
'SecurityGroupIds': [sg_id],
'TagSpecifications': [{
'ResourceType': 'instance',
'Tags': [{'Key': 'Name', 'Value': 'Sherlock-Provisioned-Instance'}]
}]
}
# Add optional params
if args.subnet_id:
launch_params['SubnetId'] = args.subnet_id
if args.tags:
try:
extra_tags = json.loads(args.tags)
launch_params['TagSpecifications'][0]['Tags'].extend(
[{'Key': k, 'Value': v} for k, v in extra_tags.items()]
)
except json.JSONDecodeError:
print("Error: --tags must be valid JSON (e.g., '{\"Env\": \"Prod\"}').", file=sys.stderr)
sys.exit(1)
# Launch instance
response = ec2_client.run_instances(**launch_params)
instance_id = response['Instances'][0]['InstanceId']
print(f"Launched instance: {instance_id}")
return instance_id
def wait_for_instance(ec2_client, instance_id):
"""Wait for instance to be running and print details."""
waiter = ec2_client.get_waiter('instance_running')
waiter.wait(InstanceIds=[instance_id])
# Get instance details
response = ec2_client.describe_instances(InstanceIds=[instance_id])
instance = response['Reservations'][0]['Instances'][0]
print("\nInstance Details:")
print(f" ID: {instance['InstanceId']}")
print(f" State: {instance['State']['Name']}")
if 'PublicIpAddress' in instance:
print(f" Public IP: {instance['PublicIpAddress']}")
if 'PublicDnsName' in instance:
print(f" Public DNS: {instance['PublicDnsName']}")
print(f" Launch Time: {instance['LaunchTime']}")
def main():
parser = argparse.ArgumentParser(description="Automate EC2 provisioning with Boto3.")
parser.add_argument('--region', default='us-east-1', help='AWS Region (default: us-east-1)')
parser.add_argument('--ami-id', required=True, help='AMI ID to use')
parser.add_argument('--instance-type', default='t3.micro', help='Instance type (default: t3.micro)')
parser.add_argument('--key-name', required=True, help='EC2 Key Pair name')
parser.add_argument('--security-group-name', default='sherlock-sg', help='Security Group name (default: sherlock-sg)')
parser.add_argument('--subnet-id', help='Subnet ID (uses default VPC if omitted)')
parser.add_argument('--min-count', type=int, default=1, help='Min instances to launch (default: 1)')
parser.add_argument('--max-count', type=int, default=1, help='Max instances to launch (default: 1)')
parser.add_argument('--tags', help='Extra tags as JSON (e.g., \'{"Env": "Prod"}\')')
args = parser.parse_args()
try:
# Create EC2 client
ec2_client = boto3.client('ec2', region_name=args.region)
# Launch and wait
instance_id = launch_ec2_instance(ec2_client, args)
wait_for_instance(ec2_client, instance_id)
print("\nProvisioning complete! Connect via: ssh -i your-key.pem ec2-user@<public-ip>")
except NoCredentialsError:
print("Error: AWS credentials not found. Configure via `aws configure` or environment variables.", file=sys.stderr)
sys.exit(1)
except ClientError as e:
print(f"AWS Error: {e}", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"Unexpected error: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
Key Features
- CLI-Driven: Easy to use with arguments for flexibility.
- Idempotent Security Group: Creates only if missing, authorizes SSH (restrict
CidrIp in production!).
- Waiters: Uses Boto3 waiters for reliable status polling.
- Tagging: Built-in tags + optional JSON extra tags.
- Error Handling: Catches AWS/client errors gracefully.
- Default VPC: Falls back to default VPC/subnet unless specified.
- Extensible: Add more resources (e.g., EBS volumes) by extending
launch_ec2_instance.
Testing
- Install:
pip install boto3
- Run: Use example command above (replace AMI/Key with yours).
- Cleanup: Use AWS Console/CLI:
aws ec2 terminate-instances --instance-ids i-xxx and delete SG.
This script is production-ready for basic automation. For advanced use (e.g., ASGs, Load Balancers), extend or use CloudFormation via Boto3. Questions? Ask Sherlock! 🚀