Initiating the Analysis
I'm starting by zeroing in on the core request: a Python script for cloud provisioning. The presence of Boto3 firmly establishes AWS as the target environment. Now I'll drill down to clarify the specifics of the provisioning task itself.
Clarifying the Objectives
I'm now prioritizing the functionality: a focus on practical utility. I've decided to move away from the overly simplistic "Hello World" EC2 approach and instead concentrate on a more useful, albeit slightly more involved, workflow. This includes key pair creation, security group setup, and finally, launching the EC2 instance. This approach gives the user something immediately functional.
Expanding the Implementation
Now I'm focusing on the implementation's nuts and bolts. I've begun to flesh out the code structure. Exception handling is key, especially when dealing with pre-existing resources like key pairs. I'm also grappling with the specifics: region-specific AMIs. The code is taking shape, and I'm ensuring it's robust and adaptable, not just functional.
Outlining the Implementation
I'm now outlining the steps to translate the design into working code. I will include error handling. Crucially, I'm integrating best practices, such as leveraging the SSM Parameter Store for AMI retrieval, ensuring the script's flexibility and portability. The goal is to provide a complete, readily usable solution.
Deconstructing the Process
I'm now fully dissecting the original request, breaking down the user's needs to ensure I haven't missed any essential elements. The provided solution serves as a benchmark and a guide, allowing me to ensure completeness and identify any areas I might have overlooked. I am considering potential edge cases and error handling strategies.
This is a comprehensive Python script using Boto3 to provision an AWS EC2 instance.
To make this script distinct and robust—rather than just launching a server in a void—it performs a complete workflow:
- Dynamic AMI Lookup: Fetches the latest Amazon Linux 2 image ID (so you don't have to hardcode region-specific IDs).
- Key Pair Management: Creates an SSH key pair and saves the
.pem file locally.
- Security Check: Creates a Security Group to allow SSH access.
- Provisioning: Launches the instance with tags.
- Validation: Waits for the instance to start and outputs the Public IP.
Prerequisites
- Install Boto3:
pip install boto3
- AWS Credentials: Ensure you have your credentials set up (usually via
aws configure or environment variables AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY).
The Python Script (provision_ec2.py)
import boto3
import botocore
import os
import time
# --- Configuration ---
AWS_REGION = "us-east-1"
INSTANCE_TYPE = "t2.micro"
KEY_PAIR_NAME = "automation-key"
SEC_GROUP_NAME = "automation-sec-group"
INSTANCE_NAME = "Automated-Server-01"
def get_latest_ami(region):
"""
Fetches the latest Amazon Linux 2 AMI ID using SSM Parameter Store.
This ensures the script works without hardcoding old AMI IDs.
"""
ssm = boto3.client('ssm', region_name=region)
response = ssm.get_parameter(
Name='/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2',
WithDecryption=True
)
return response['Parameter']['Value']
def create_key_pair(ec2_client, key_name):
"""
Creates a Key Pair and saves the .pem file locally.
"""
try:
key_pair = ec2_client.create_key_pair(KeyName=key_name)
private_key = key_pair['KeyMaterial']
filename = f"{key_name}.pem"
with open(filename, 'w') as file:
file.write(private_key)
# Set file permissions to read-only for owner (required for SSH)
os.chmod(filename, 0o400)
print(f"✅ Key Pair '{key_name}' created. Saved to {filename}")
return key_name
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidKeyPair.Duplicate':
print(f"⚠️ Key Pair '{key_name}' already exists. Using existing key.")
return key_name
else:
raise e
def create_security_group(ec2_resource, group_name):
"""
Creates a security group allowing SSH (Port 22) traffic.
"""
try:
# Check if it already exists
sgs = list(ec2_resource.security_groups.filter(GroupNames=[group_name]))
if sgs:
print(f"⚠️ Security Group '{group_name}' already exists. Using existing group.")
return sgs[0].id
# Create new group
sg = ec2_resource.create_security_group(
GroupName=group_name,
Description='Created by Python Automation Script'
)
# Allow SSH (Port 22)
sg.authorize_ingress(
IpPermissions=[{
'IpProtocol': 'tcp',
'FromPort': 22,
'ToPort': 22,
'IpRanges': [{'CidrIp': '0.0.0.0/0'}]
}]
)
print(f"✅ Security Group '{group_name}' created (ID: {sg.id})")
return sg.id
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == 'InvalidGroup.Duplicate':
# Fallback if the filter check missed it (edge case)
print(f"⚠️ Security Group '{group_name}' already exists.")
return ec2_resource.security_groups.filter(GroupNames=[group_name]).list()[0].id
raise e
def provision_instance():
ec2_client = boto3.client('ec2', region_name=AWS_REGION)
ec2_resource = boto3.resource('ec2', region_name=AWS_REGION)
print(f"🚀 Starting provisioning in {AWS_REGION}...")
# 1. Get Image ID
ami_id = get_latest_ami(AWS_REGION)
print(f"ℹ️ Using AMI: {ami_id}")
# 2. Create Key Pair
create_key_pair(ec2_client, KEY_PAIR_NAME)
# 3. Create Security Group
sg_id = create_security_group(ec2_resource, SEC_GROUP_NAME)
# 4. Launch Instance
print("⏳ Launching EC2 Instance...")
instances = ec2_resource.create_instances(
ImageId=ami_id,
MinCount=1,
MaxCount=1,
InstanceType=INSTANCE_TYPE,
KeyName=KEY_PAIR_NAME,
SecurityGroupIds=[sg_id],
TagSpecifications=[{
'ResourceType': 'instance',
'Tags': [{'Key': 'Name', 'Value': INSTANCE_NAME}]
}]
)
instance = instances[0]
# 5. Wait for Instance to be Running
print(f"⏳ Waiting for instance {instance.id} to initialize...")
instance.wait_until_running()
# Reload instance attributes to get Public IP
instance.reload()
print("-" * 50)
print("✅ Resource Provisioning Complete!")
print(f" Instance ID: {instance.id}")
print(f" State: {instance.state['Name']}")
print(f" Public DNS: {instance.public_dns_name}")
print(f" Public IP: {instance.public_ip_address}")
print("-" * 50)
print("To connect, run:")
print(f"ssh -i {KEY_PAIR_NAME}.pem ec2-user@{instance.public_ip_address}")
if __name__ == '__main__':
provision_instance()
How this script works:
- Resources vs Clients:
boto3.client: Used for low-level AWS service access (e.g., fetching the AMI ID from Parameter Store, creating Key Pairs).
boto3.resource: A higher-level, object-oriented abstraction. Used for managing the instance object and security groups.
- AMI Strategy: Instead of hardcoding an ID like
ami-0abcdef... (which changes often and differs by region), we query the AWS SSM Parameter Store. This is best practice for fetching the "latest Amazon Linux 2" image dynamically.
- Idempotency Handling: The
create_key_pair and create_security_group functions interact with existing resources. If you run the script twice, it won't crash; it detects that the key/group already exists and uses them.
- Waiters: The command
instance.wait_until_running() is crucial. AWS API calls are asynchronous. Without this, the script would finish before the server actually has an IP address, resulting in empty output.
- Tagging: It applies
TagSpecifications during creation. Tags are essential for cost allocation and resource management in real environments.
Cleaning Up (Teardown)
Since this creates real resources that cost money (though t2.micro is free-tier eligible), you can delete them using the AWS Console or this simple Python snippet:
import boto3
ec2 = boto3.resource('ec2', region_name='us-east-1')
# Terminate Instance
print("Terminating instances...")
ec2.instances.filter(Filters=[{'Name': 'tag:Name', 'Values': ['Automated-Server-01']}]).terminate()
# Note: You must wait for the instance to terminate before deleting the Security Group