Clarifying automation request
The user wants a Python script for automating cloud resource provisioning with Boto3. That’s somewhat broad, so I might need to clarify what specific resources they want to provision. I could provide an example by creating a VPC, subnet, security group, EC2 instance, and possibly an S3 bucket. The script should be modular, configuration-driven, and reusable, while also instructing the user on proper credential management using IAM roles. I'll focus on delivering a concise script with sufficient guidance included.Designing a provisioning script
I’m planning a script that uses Boto3 to automate the creation of various resources like a VPC, subnet, internet gateway, route table, security group, EC2 instance, and S3 bucket. I'd like to include resource tagging for clarity. For configuration, I could either use a dictionary at the top or load from a YAML file. The script would import necessary libraries and set up a configuration example defining key parameters like region and resources. I’ll outline the functions needed and create a main function for provisioning, focusing primarily on that task.Simplifying the script design
I’m considering a simpler approach for the script, focusing on functions without a command-line interface (CLI), although users might adapt it later. The task of "automating cloud resource provisioning" suggests a general pattern, and it could be beneficial to include a CLI example. I need to handle specific edge cases, like region-specific considerations for S3 bucket creation. It’s also important to ensure that I handle waiters for tasks like instance startup.
I'll write the code with comments, keeping text explanations concise. My final output will include a small preface, a "requirements" section, the full script in a code block, and a brief note on customization and credential setup while emphasizing security and avoiding hardcoded credentials. The script will be named 'provision_aws_resources.py'.Implementing AMI retrieval and VPC creation
I’m planning to retrieve the latest Amazon Linux 2023 AMI using the SSM parameter system, which seems like the modern approach. I’ll write a function called get_latest_ami that uses the SSM client to fetch this parameter. I’ll also include error handling with try/except to ensure robustness.
Next, I’m creating the ensure_vpc function to check for existing VPCs based on CIDR blocks and tags. If a VPC doesn’t exist, the function will create a new one. While this may not be fully idempotent, I think it’s fine for the scripting purpose. There's also a step to enable DNS hostnames for the VPC, which I’ll include as well.Building the infrastructure script
I’m finalizing the script to create our cloud infrastructure. First, I’ll modify the VPC attributes, which will require two calls. Then, I’ll create a subnet, internet gateway, and route table, with appropriate configurations to ensure public access. After setting up a security group, I’ll include the function to compute the AMI ID and create an EC2 instance with correct network interfaces.
I also need to handle the S3 bucket creation based on the region and ensure the bucket name is unique. While I want to keep the script simple, I'll suggest a configuration dictionary at the top for user modifications. I won't dive deeply into CLI arguments, focusing instead on clarity. I’ll instruct users to set their AWS credentials accordingly, aiming for a user-friendly output. Below is a self‑contained example Python script that uses Boto3 to provision a small AWS environment:
- VPC
- Public subnet
- Internet gateway + route table
- Security group (SSH + HTTP)
- EC2 instance (Amazon Linux)
- S3 bucket
You can extend or adapt this pattern for other resources.
Prerequisites
- Install Boto3:
pip install boto3
-
Configure AWS credentials (one of):
aws configure (AWS CLI)
- Environment variables
AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION
- EC2 instance / role with permissions
-
Make sure you:
- Have an existing EC2 key pair (
CONFIG["key_name"]).
- Use a globally unique S3 bucket name (
CONFIG["bucket_name"]).
Script: provision_aws_resources.py
#!/usr/bin/env python3
"""
Provision basic AWS infrastructure with Boto3:
- VPC
- Public subnet
- Internet gateway and route
- Security group
- EC2 instance
- S3 bucket
Edit the CONFIG dictionary before running.
"""
import boto3
from botocore.exceptions import ClientError
# ---------------------- configuration ---------------------- #
CONFIG = {
"profile": None, # e.g. "default" or "myprofile". None => use default chain
"region": "us-east-1",
"project_name": "demo-provisioning",
"vpc_cidr": "10.0.0.0/16",
"public_subnet_cidr": "10.0.1.0/24",
# Must exist in your account/region
"key_name": "my-existing-keypair",
"instance_type": "t3.micro",
# S3 bucket name must be globally unique
"bucket_name": "my-unique-bucket-name-123456",
}
# ---------------------- helpers ---------------------- #
def get_session(config: dict) -> boto3.session.Session:
"""Return a boto3 Session using optional profile and region."""
return boto3.Session(
profile_name=config.get("profile"),
region_name=config["region"],
)
def get_latest_amazon_linux_ami(region: str) -> str:
"""
Get latest Amazon Linux 2023 AMI via SSM Parameter Store.
Adjust parameter name if you want different OS/arch.
"""
ssm = boto3.client("ssm", region_name=region)
param_name = "/aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64"
resp = ssm.get_parameter(Name=param_name)
return resp["Parameter"]["Value"]
# ---------------------- provisioning functions ---------------------- #
def create_vpc(ec2_resource, ec2_client, cidr_block: str, project_name: str):
print(f"Creating VPC ({cidr_block})...")
vpc = ec2_resource.create_vpc(CidrBlock=cidr_block)
vpc.wait_until_available()
vpc.create_tags(Tags=[
{"Key": "Name", "Value": f"{project_name}-vpc"},
{"Key": "Project", "Value": project_name},
])
# Enable DNS
ec2_client.modify_vpc_attribute(
VpcId=vpc.id,
EnableDnsSupport={"Value": True}
)
ec2_client.modify_vpc_attribute(
VpcId=vpc.id,
EnableDnsHostnames={"Value": True}
)
print(f"VPC created: {vpc.id}")
return vpc
def create_public_subnet(vpc, ec2_client, cidr_block: str, project_name: str):
print(f"Creating public subnet ({cidr_block})...")
subnet = vpc.create_subnet(CidrBlock=cidr_block)
subnet.wait_until_available()
subnet.create_tags(Tags=[
{"Key": "Name", "Value": f"{project_name}-public-subnet"},
{"Key": "Project", "Value": project_name},
])
# Auto-assign public IPs
ec2_client.modify_subnet_attribute(
SubnetId=subnet.id,
MapPublicIpOnLaunch={"Value": True}
)
print(f"Public subnet created: {subnet.id}")
return subnet
def create_internet_gateway(ec2_resource, vpc, project_name: str):
print("Creating Internet Gateway...")
igw = ec2_resource.create_internet_gateway()
igw.create_tags(Tags=[
{"Key": "Name", "Value": f"{project_name}-igw"},
{"Key": "Project", "Value": project_name},
])
vpc.attach_internet_gateway(InternetGatewayId=igw.id)
print(f"Internet Gateway created and attached: {igw.id}")
return igw
def create_public_route_table(vpc, igw, subnet, project_name: str):
print("Creating route table and route to Internet Gateway...")
route_table = vpc.create_route_table()
route_table.create_tags(Tags=[
{"Key": "Name", "Value": f"{project_name}-public-rt"},
{"Key": "Project", "Value": project_name},
])
route_table.create_route(
DestinationCidrBlock="0.0.0.0/0",
GatewayId=igw.id
)
route_table.associate_with_subnet(SubnetId=subnet.id)
print(f"Route table created and associated: {route_table.id}")
return route_table
def create_security_group(vpc, ec2_client, project_name: str):
sg_name = f"{project_name}-sg"
print(f"Creating security group '{sg_name}'...")
resp = ec2_client.create_security_group(
GroupName=sg_name,
Description="Demo security group (SSH and HTTP allowed)",
VpcId=vpc.id,
TagSpecifications=[{
"ResourceType": "security-group",
"Tags": [
{"Key": "Name", "Value": sg_name},
{"Key": "Project", "Value": project_name},
],
}]
)
sg_id = resp["GroupId"]
# Allow SSH from anywhere (0.0.0.0/0) – change in production!
# Allow HTTP from anywhere
ec2_client.authorize_security_group_ingress(
GroupId=sg_id,
IpPermissions=[
{
"IpProtocol": "tcp",
"FromPort": 22,
"ToPort": 22,
"IpRanges": [{"CidrIp": "0.0.0.0/0", "Description": "SSH from anywhere"}],
},
{
"IpProtocol": "tcp",
"FromPort": 80,
"ToPort": 80,
"IpRanges": [{"CidrIp": "0.0.0.0/0", "Description": "HTTP from anywhere"}],
},
]
)
print(f"Security group created: {sg_id}")
return sg_id
def launch_ec2_instance(ec2_resource, config: dict, subnet_id: str, sg_id: str, ami_id: str):
print("Launching EC2 instance...")
instances = ec2_resource.create_instances(
ImageId=ami_id,
InstanceType=config["instance_type"],
KeyName=config["key_name"],
MinCount=1,
MaxCount=1,
NetworkInterfaces=[{
"SubnetId": subnet_id,
"DeviceIndex": 0,
"AssociatePublicIpAddress": True,
"Groups": [sg_id],
}],
TagSpecifications=[{
"ResourceType": "instance",
"Tags": [
{"Key": "Name", "Value": f"{config['project_name']}-instance"},
{"Key": "Project", "Value": config["project_name"]},
],
}]
)
instance = instances[0]
print(f"Waiting for instance to be running ({instance.id})...")
instance.wait_until_running()
instance.reload()
print(f"Instance running: {instance.id}, public IP: {instance.public_ip_address}")
return instance
def create_s3_bucket(s3_client, bucket_name: str, region: str, project_name: str):
print(f"Creating S3 bucket '{bucket_name}' in {region}...")
create_kwargs = {"Bucket": bucket_name}
if region != "us-east-1":
create_kwargs["CreateBucketConfiguration"] = {"LocationConstraint": region}
s3_client.create_bucket(**create_kwargs)
# Add basic tags (via put_bucket_tagging)
s3_client.put_bucket_tagging(
Bucket=bucket_name,
BucketTagging={
"TagSet": [
{"Key": "Name", "Value": f"{project_name}-bucket"},
{"Key": "Project", "Value": project_name},
]
},
)
print(f"Bucket created: {bucket_name}")
return bucket_name
# ---------------------- main orchestration ---------------------- #
def provision_infrastructure(config: dict):
session = get_session(config)
region = config["region"]
ec2_resource = session.resource("ec2")
ec2_client = session.client("ec2")
s3_client = session.client("s3")
try:
# 1. VPC
vpc = create_vpc(ec2_resource, ec2_client, config["vpc_cidr"], config["project_name"])
# 2. Subnet
subnet = create_public_subnet(vpc, ec2_client, config["public_subnet_cidr"], config["project_name"])
# 3. Internet Gateway + Route Table
igw = create_internet_gateway(ec2_resource, vpc, config["project_name"])
route_table = create_public_route_table(vpc, igw, subnet, config["project_name"])
# 4. Security Group
sg_id = create_security_group(vpc, ec2_client, config["project_name"])
# 5. AMI
ami_id = get_latest_amazon_linux_ami(region)
print(f"Using AMI: {ami_id}")
# 6. EC2 Instance
instance = launch_ec2_instance(
ec2_resource,
config,
subnet_id=subnet.id,
sg_id=sg_id,
ami_id=ami_id
)
# 7. S3 Bucket
bucket_name = create_s3_bucket(
s3_client,
config["bucket_name"],
region,
config["project_name"]
)
print("\nProvisioning complete.")
print(f"VPC ID: {vpc.id}")
print(f"Subnet ID: {subnet.id}")
print(f"IGW ID: {igw.id}")
print(f"Route Table: {route_table.id}")
print(f"SecurityGroup: {sg_id}")
print(f"Instance ID: {instance.id}")
print(f"Instance IP: {instance.public_ip_address}")
print(f"S3 Bucket: {bucket_name}")
except ClientError as e:
print(f"AWS ClientError: {e}")
raise
except Exception as e:
print(f"Unexpected error: {e}")
raise
if __name__ == "__main__":
provision_infrastructure(CONFIG)
How to use
- Save as
provision_aws_resources.py.
- Edit
CONFIG near the top:
- Set
profile (optional) and region.
- Set an existing
key_name.
- Set a unique
bucket_name.
- Run:
python provision_aws_resources.py
If you tell me which specific resources or patterns you want (e.g., multiple subnets, RDS, autoscaling, tags from a YAML file), I can adapt this script to match that design.