The user is asking for a Python script to automate cloud resource provisioning using Boto3.
Boto3 is the Amazon Web Services (AWS) SDK for Python. It allows Python developers to write software that makes use of services like Amazon S3, Amazon EC2, DynamoDB, etc.
"Cloud resource provisioning" is a broad term. It could mean creating EC2 instances, S3 buckets, VPCs, RDS databases, etc.
To provide a useful answer, I need to create a script that demonstrates common provisioning tasks, specifically focusing on AWS (since Boto3 is requested).
Scope of the Script:
Prerequisites: I need to mention that AWS credentials and Boto3 installation are required.
Configuration: It's best practice to separate configuration (region, instance type, etc.) from the logic.
Core Functionality:
EC2 Instance: This is the most common "resource" people think of. I should include a function to create an instance.
S3 Bucket: Another very common resource.
VPC/Security Group: To make the EC2 instance actually useful, it needs a network context. I should probably include creating a Security Group at least.
Idempotency: Good infrastructure-as-code practices suggest checking if a resource exists before creating it, or handling the "AlreadyExists" error gracefully. For a simple example script, handling the error is usually sufficient, but checking is nicer. Let's aim for a balance—mostly just creating them but handling the "BucketAlreadyExists" or "InvalidGroup.Duplicate" errors.
Drafting the Code Structure:
Imports:import boto3, botocore.
Class vs. Functions: A class CloudProvisioner or just a set of functions? A class helps keep state (like the region or specific clients) but functions are simpler for a script. Let's use functions for simplicity, passing the boto3 clients around.
Specific Resources to Create:
S3 Bucket: Easy to start with.
Input: Bucket name.
Logic: Create bucket. Handle 409 (conflict).
Security Group: Needed for EC2.
Input: Group name, description, VPC ID (optional, use default if not provided).
Logic: Create SG. Add ingress rule (Port 22 for SSH is standard).
EC2 Instance:
Input: Image ID (AMI), Instance Type, Key Name, Security Group ID.
Logic: Run instances. Wait until running.
Refining the Script:
I need to make sure the user knows they need to replace placeholders (like AMI IDs, Key Pair names).
I should include a "main" block to execute the flow.
Safety & Security:
Hardcoding credentials is bad. I will assume the user has the AWS CLI configured or environment variables set.
Opening port 22 (SSH) to the world (0.0.0.0/0) is common in tutorials but bad practice. I'll add a comment warning about it, but do it for the script to work easily.
Self-Correction: Using a specific AMI ID is tricky because they vary by region. I should probably provide a function to get the latest Amazon Linux 2 AMI dynamically to make the script more robust.
Step-by-Step Plan:
Setup: Install instructions (pip install boto3).
Script:
Initialize Boto3 clients for EC2 and S3.
Function 1: Create S3 Bucket.
Function 2: Create Security Group (allowing SSH).
Function 3: Get latest AMI ID (so the script works regardless of region without user lookup).
Function 4: Launch EC2 Instance using the SG and AMI.
Cleanup (Optional): Maybe mention how to delete them, or just focus on provisioning as requested. The prompt just asks for provisioning.
Output: Print status messages.
Writing the Code (Mental Draft):
python
import boto3
import botocore
def create_s3_bucket(s3_client, bucket_name, region):
try:
# specific handling for us-east-1 vs others
s3_client.create_bucket(Bucket=bucket_name)
print(f"Bucket {bucket_name} created")
except s3_client.exceptions.BucketAlreadyOwnedByYou:
print("Bucket exists")
# ... similar for EC2 ...
Polishing:
Make the script modular and commented.
Ensure the Boto3 resource vs client distinction is clear or consistent. client is lower-level but maps 1:1 with API. resource is higher-level. For provisioning, client is often preferred for explicit control, but resource makes waiting easier. I'll stick to client for creation and specific actions, as it's more standard for provisioning scripts that might need specific error codes.
Let's verify the AMI lookup logic.
ec2.describe_images(Owners=['amazon'], Filters=[{'Name': 'name', 'Values': ['amzn2-ami-hvm-*-x86_64-gp2']}]). This is a safe way to get an image.
Final Structure:
Introduction.
Prerequisites section.
The Python script.
Explanation of what the script does.
How to run it.
This looks solid. I will generate the response based on this plan.
Here is a comprehensive Python script that demonstrates how to automate the provisioning of a basic AWS infrastructure stack.
This script uses Boto3 (the AWS SDK for Python) to provision the following resources:
S3 Bucket: For storage.
Security Group: To define firewall rules (allowing SSH).
EC2 Key Pair: For secure access to the server.
EC2 Instance: A virtual server running Amazon Linux.
Prerequisites
Before running the script, ensure you have the following:
AWS Account: You need valid AWS credentials.
Boto3 Installed: Run pip install boto3.
AWS CLI Configured: It is best practice to use the AWS CLI to set your credentials (aws configure) rather than hardcoding keys in the script. Alternatively, set the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables.
The Python Script
Save this code as provision_resources.py.
python
Explanation of the Code
Clients: We create ec2 and s3 clients. These objects allow us to call AWS API methods.
Error Handling: We wrap calls in try...except blocks. AWS APIs often return specific errors (like BucketAlreadyExists or InvalidKeyPair.Duplicate). The script handles these gracefully so it doesn't crash if a resource already exists.
S3 Bucket: S3 bucket names must be globally unique across all AWS accounts. The script appends a random number suffix to ensure uniqueness.
Key Pairs: When creating a Key Pair via API, AWS returns the private key material only once. The script saves this to a .pem file locally so you can use it to SSH later.
Security Groups: We create a firewall group and explicitly add an ingress rule allowing traffic on port 22 (SSH).
EC2 Instance:
AMI ID: We specify an Amazon Machine Image ID. Note that AMI IDs differ by region.
User Data: This is a Bash script passed as a string. AWS runs this automatically the first time the instance boots. In this example, it installs a web server.
Waiters: ec2.get_waiter('instance_running') is a powerful Boto3 feature that pauses the script until the instance is fully booted, preventing you from trying to connect too early.
Cleanup
Running this script will create real resources that cost money (though t2.micro is usually in the free tier). To delete these resources, you should go to the AWS Console and:
Terminate the EC2 instance.
Delete the Key Pair and Security Group (you must delete the Key Pair file from your local computer too).
Empty and Delete the S3 bucket.
import boto3
import botocore.exceptions
import base64
import time
import random
import string
# -----------------------------------------------------------------------
# CONFIGURATION
# -----------------------------------------------------------------------
REGION = 'us-east-1'
# Generate a unique suffix to avoid naming conflicts globally (S3 buckets must be unique)
UNIQUE_SUFFIX = ''.join(random.choices(string.digits, k=6))
BUCKET_NAME = f'my-auto-bucket-{UNIQUE_SUFFIX}'
KEY_NAME = f'my-auto-key-{UNIQUE_SUFFIX}'
SG_NAME = 'my-auto-security-group'
INSTANCE_TYPE = 't2.micro'
# Amazon Linux 2023 AMI ID (This changes over time and by region.
# Ideally, use describe_images to fetch this dynamically, but for this script
# we use a static ID for us-east-1 as an example).
# If this fails, check the AWS console for the latest AMI ID.
AMI_ID = 'ami-0c7217cdde317cfec'
# -----------------------------------------------------------------------
# INITIALIZATION
# -----------------------------------------------------------------------
# Initialize Boto3 clients
ec2 = boto3.client('ec2', region_name=REGION)
s3 = boto3.client('s3', region_name=REGION)
def create_s3_bucket():
print(f"--- Creating S3 Bucket: {BUCKET_NAME} ---")
try:
# Handle us-east-1 specificity (CreateBucketConfiguration is not allowed in us-east-1)
if REGION == 'us-east-1':
s3.create_bucket(Bucket=BUCKET_NAME)
else:
s3.create_bucket(
Bucket=BUCKET_NAME,
CreateBucketConfiguration={'LocationConstraint': REGION}
)
print(f"Bucket {BUCKET_NAME} created successfully.")
except botocore.exceptions.ClientError as e:
print(f"Error creating bucket: {e}")
def create_key_pair():
print(f"--- Creating EC2 Key Pair: {KEY_NAME} ---")
try:
response = ec2.create_key_pair(KeyName=KEY_NAME)
# Save the private key to a file locally
key_material = response['KeyMaterial']
filename = f"{KEY_NAME}.pem"
with open(filename, 'w') as f:
f.write(key_material)
print(f"Key pair created and saved to {filename}. KEEP THIS SAFE.")
except botocore.exceptions.ClientError as e:
if 'InvalidKeyPair.Duplicate' in str(e):
print("Key pair already exists. Using existing key.")
else:
print(f"Error creating key pair: {e}")
def create_security_group():
print(f"--- Creating Security Group: {SG_NAME} ---")
try:
response = ec2.create_security_group(
GroupName=SG_NAME,
Description='Security group created by Boto3 script'
)
sg_id = response['GroupId']
print(f"Security Group created with ID: {sg_id}")
# Add rule to allow SSH (Port 22) from anywhere (0.0.0.0/0)
# WARNING: In production, restrict this to your specific IP.
ec2.authorize_security_group_ingress(
GroupId=sg_id,
IpPermissions=[
{
'IpProtocol': 'tcp',
'FromPort': 22,
'ToPort': 22,
'IpRanges': [{'CidrIp': '0.0.0.0/0'}]
}
]
)
print("Ingress rule (SSH) added.")
return sg_id
except botocore.exceptions.ClientError as e:
if 'InvalidGroup.Duplicate' in str(e):
print("Security Group already exists. Retrieving ID...")
response = ec2.describe_security_groups(GroupNames=[SG_NAME])
return response['SecurityGroups'][0]['GroupId']
else:
print(f"Error creating security group: {e}")
return None
def launch_ec2_instance(sg_id):
print(f"--- Launching EC2 Instance ---")
if not sg_id:
print("Skipping EC2 launch due to missing Security Group ID.")
return
# User Data: Script to run when the instance starts (e.g., install httpd)
user_data_script = """#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd
echo "<h1>Provisioned by Boto3</h1>" > /var/www/html/index.html
"""
try:
response = ec2.run_instances(
ImageId=AMI_ID,
MinCount=1,
MaxCount=1,
InstanceType=INSTANCE_TYPE,
KeyName=KEY_NAME,
SecurityGroupIds=[sg_id],
UserData=user_data_script,
TagSpecifications=[
{
'ResourceType': 'instance',
'Tags': [{'Key': 'Name', 'Value': 'Boto3-Instance'}]
}
]
)
instance_id = response['Instances'][0]['InstanceId']
print(f"Instance launched successfully: {instance_id}")
print("Waiting for instance to initialize...")
# Waiter ensures the script pauses until the instance is running
waiter = ec2.get_waiter('instance_running')
waiter.wait(InstanceIds=[instance_id])
# Get Public IP
desc = ec2.describe_instances(InstanceIds=[instance_id])
public_ip = desc['Reservations'][0]['Instances'][0].get('PublicIpAddress')
public_dns = desc['Reservations'][0]['Instances'][0].get('PublicDnsName')
print(f"Instance is RUNNING!")
print(f"Access via SSH: ssh -i {KEY_NAME}.pem ec2-user@{public_ip}")
print(f"Web Server (if user-data ran): http://{public_dns}")
except botocore.exceptions.ClientError as e:
print(f"Error launching instance: {e}")
# -----------------------------------------------------------------------
# MAIN EXECUTION
# -----------------------------------------------------------------------
if __name__ == "__main__":
print("Starting Cloud Provisioning...")
# 1. Create S3 Bucket
create_s3_bucket()
# 2. Create Key Pair for SSH
create_key_pair()
# 3. Create Security Group and get ID
security_group_id = create_security_group()
# 4. Launch EC2 Instance
launch_ec2_instance(security_group_id)
print("\n--- Provisioning Complete ---")