β‘ Quick Reference
Keep the momentum going β everything you need on LearnXOps in one place:
- π Courses β Video courses & AI-built courses
- π Ebooks β Community ebooks & your own
- π§ͺ All Labs & Challenges β DevOps, Cloud, SRE & more
- βΈοΈ Kubernetes Labs & Playground β kind clusters, playground & challenges
- π€ AI Agent & Bot Labs β OpenClaw Β· Hermes Β· CrewAI Β· LangGraph Β· MCP
Hey β It's Sandip Das π
Boto3 is the gateway to AWS Cloud automation, allowing developers and DevOps engineers to manage cloud resources programmatically with Python. From provisioning EC2 instances to automating S3 backups and security policies, Boto3 simplifies cloud management, improves efficiency, and reduces manual effort in AWS operations.
π Before we begin... a big thank you to today's sponsor Sloth Bytes
Subscribe to Sloth Bytes for amazing programming concepts and examples
Learning points:
πΉ Cloud Automation with Boto3 β Managing AWS services (EC2, S3, IAM, Lambda, RDS) using Python scripts.
πΉ Automating Cloud Monitoring & Logging β Writing Python scripts for log parsing, system monitoring, and alerting.
πΉ Security & Compliance β Automating security audits, IAM role management, and compliance checks.
π§ Learn here:
Hands-on Python Boto3
ποΈ Resources:
π Boto3 Official Docs β AWS SDK for Python
π 20 Best Python Scripts to Automate Your Daily Tasks in AWS
Initial Tasks:
β Task 1: Install boto3 (pip install boto3) and configure AWS credentials (aws configure).
π₯ Challenges
πΉ Challenge 1: Write a Python script that provisions an EC2 instance, a new security group, and a key pair. The same script should connect to ec2 after creation to check that everything is working fine. (The key pair should be generated via the Python script and used for the EC2 SSH connection.)
πΉ Challenge 2: Automate S3 lifecycle policies using boto3 (e.g., move files to Glacier after 30 days).
πΉ Challenge 3: Create a script that starts or stops all EC2 instances in a specific AWS region.
πΉ Challenge 4: Write a Python program that checks for unused IAM users and disables them.
πΉ Challenge 5: Implement a log monitoring system that scans EC2 instances' /var/log for error messages and sends alerts via email (AWS SES) and Slack.
πΉ Challenge 6: Automate DNS record updates in AWS Route 53 using Python.
πΉ Challenge 7: Write a script that triggers an AWS Lambda function using boto3.
πΉ Challenge 8: Use boto3 to fetch AWS billing data, and generate a cost analysis report in PDF format
β Solutions
β Challenge 1: Write a Python script that provisions an EC2 instance, a new security group, and a key pair.
# Step 1: Install Required Dependencies
# pip install boto3 paramiko requests
import os
import boto3
import paramiko
import requests
# AWS Configuration
AWS_REGION = "us-east-1"
INSTANCE_TYPE = "t3.micro"
# Latest Ubuntu 24.04 LTS AMI for the region, read from AWS's public SSM parameter
UBUNTU_AMI_PARAM = "/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id"
SECURITY_GROUP_NAME = "my-ec2-security-group"
KEY_PAIR_NAME = "my-ec2-keypair"
SSH_USERNAME = "ubuntu" # ec2-user on Amazon Linux
# Initialize AWS Clients
ec2_client = boto3.client("ec2", region_name=AWS_REGION)
ec2_resource = boto3.resource("ec2", region_name=AWS_REGION)
ssm_client = boto3.client("ssm", region_name=AWS_REGION)
def get_ami_id():
return ssm_client.get_parameter(Name=UBUNTU_AMI_PARAM)["Parameter"]["Value"]
def create_key_pair():
print("π Creating key pair...")
key_pair = ec2_client.create_key_pair(KeyName=KEY_PAIR_NAME, KeyType="rsa")
key_file = f"{KEY_PAIR_NAME}.pem"
with open(key_file, "w") as file:
file.write(key_pair["KeyMaterial"])
os.chmod(key_file, 0o400) # ssh refuses private keys other users can read
print(f"β
Key pair '{KEY_PAIR_NAME}' created and saved as '{key_file}'")
return key_file
def create_security_group():
print("π Creating security group...")
my_ip = requests.get("https://checkip.amazonaws.com", timeout=10).text.strip()
response = ec2_client.create_security_group(
GroupName=SECURITY_GROUP_NAME,
Description="Security group for EC2 SSH access"
)
security_group_id = response["GroupId"]
ec2_client.authorize_security_group_ingress(
GroupId=security_group_id,
IpPermissions=[{
"IpProtocol": "tcp",
"FromPort": 22,
"ToPort": 22,
# only your current public IP, not 0.0.0.0/0
"IpRanges": [{"CidrIp": f"{my_ip}/32", "Description": "SSH from my IP"}]
}]
)
print(f"β
Security group '{SECURITY_GROUP_NAME}' created with ID {security_group_id}")
return security_group_id
def launch_ec2_instance(security_group_id, key_name):
print("π Launching EC2 instance...")
instance = ec2_resource.create_instances(
ImageId=get_ami_id(),
InstanceType=INSTANCE_TYPE,
MinCount=1,
MaxCount=1,
KeyName=key_name,
SecurityGroupIds=[security_group_id],
TagSpecifications=[{
"ResourceType": "instance",
"Tags": [{"Key": "Name", "Value": "MyEC2Instance"}]
}]
)[0]
instance.wait_until_running()
instance.reload()
print(f"β
EC2 instance launched with ID: {instance.id}")
print(f"π Public IP: {instance.public_ip_address}")
return instance.id, instance.public_ip_address
def check_ec2_via_ssh(instance_ip, key_file):
print("π Connecting to EC2 instance via SSH...")
private_key = paramiko.RSAKey.from_private_key_file(key_file)
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh_client.connect(hostname=instance_ip, username=SSH_USERNAME, pkey=private_key, timeout=30)
stdin, stdout, stderr = ssh_client.exec_command("uptime")
print(f"β
SSH Successful! Uptime: {stdout.read().decode().strip()}")
except Exception as e:
print(f"β SSH Connection Failed: {e}")
finally:
ssh_client.close()
if __name__ == "__main__":
key_file = create_key_pair()
security_group_id = create_security_group()
instance_id, instance_ip = launch_ec2_instance(security_group_id, KEY_PAIR_NAME)
print("β³ Waiting for the instance status checks to pass...")
ec2_client.get_waiter("instance_status_ok").wait(InstanceIds=[instance_id])
check_ec2_via_ssh(instance_ip, key_file)β Challenge 2: Automate S3 lifecycle policies using boto3
# Step 1: Create the Python Script (s3_lifecycle.py)
import boto3
AWS_REGION = "us-east-1"
BUCKET_NAME = "your-bucket-name"
LIFECYCLE_RULE_NAME = "MoveToGlacier"
s3_client = boto3.client("s3", region_name=AWS_REGION)
def apply_s3_lifecycle_policy():
lifecycle_policy = {
"Rules": [
{
"ID": LIFECYCLE_RULE_NAME,
"Filter": {"Prefix": ""}, # whole bucket
"Status": "Enabled",
"Transitions": [
{
"Days": 30,
"StorageClass": "GLACIER"
}
],
"NoncurrentVersionTransitions": [
{
"NoncurrentDays": 30,
"StorageClass": "GLACIER"
}
]
}
]
}
try:
response = s3_client.put_bucket_lifecycle_configuration(
Bucket=BUCKET_NAME,
LifecycleConfiguration=lifecycle_policy
)
print(f"β
S3 Lifecycle policy applied successfully to '{BUCKET_NAME}'")
except Exception as e:
print(f"β Failed to apply lifecycle policy: {e}")
apply_s3_lifecycle_policy()
β Challenge 3: Create a script that starts or stops all EC2 instances in a specific AWS region
# Step 1: Create the Python Script (manage_ec2.py)
import boto3
AWS_REGION = "us-east-1"
ec2_client = boto3.client("ec2", region_name=AWS_REGION)
def get_instances(state):
"""IDs of all instances in the given state, across every page of results."""
instances = []
paginator = ec2_client.get_paginator("describe_instances")
for page in paginator.paginate(Filters=[{"Name": "instance-state-name", "Values": [state]}]):
for reservation in page["Reservations"]:
instances.extend(instance["InstanceId"] for instance in reservation["Instances"])
return instances
def manage_instances(action):
if action not in ("start", "stop"):
print("β Invalid action! Use 'start' or 'stop'.")
return
# start only stopped instances and stop only running ones
instances = get_instances("stopped" if action == "start" else "running")
if not instances:
print(f"β οΈ No EC2 instances to {action} in {AWS_REGION}.")
return
if action == "start":
ec2_client.start_instances(InstanceIds=instances)
print(f"β
Started instances: {instances}")
else:
ec2_client.stop_instances(InstanceIds=instances)
print(f"π Stopped instances: {instances}")
if __name__ == "__main__":
action = input("Enter action (start/stop): ").strip().lower()
manage_instances(action)β Challenge 4: Write a Python program that checks for unused IAM users and disables them.
# Step 1: Create the Python Script (disable_unused_iam_users.py)
import boto3
from datetime import datetime, timedelta, timezone
DAYS_INACTIVE = 90
DRY_RUN = True # review the list first, then set to False to disable
iam_client = boto3.client("iam") # IAM is a global service
cutoff = datetime.now(timezone.utc) - timedelta(days=DAYS_INACTIVE)
def last_activity(user):
"""Latest console login or access-key use; the creation date if never used."""
dates = [user["CreateDate"]]
if user.get("PasswordLastUsed"):
dates.append(user["PasswordLastUsed"])
for key in iam_client.list_access_keys(UserName=user["UserName"])["AccessKeyMetadata"]:
used = iam_client.get_access_key_last_used(AccessKeyId=key["AccessKeyId"])["AccessKeyLastUsed"]
if used.get("LastUsedDate"):
dates.append(used["LastUsedDate"])
return max(dates)
def get_unused_iam_users():
unused_users = []
for page in iam_client.get_paginator("list_users").paginate():
for user in page["Users"]:
last = last_activity(user)
if last < cutoff:
unused_users.append((user["UserName"], last))
return unused_users
def disable_user(user_name):
# remove console access (the password can't be recovered; set a new one to re-enable)
try:
iam_client.delete_login_profile(UserName=user_name)
except iam_client.exceptions.NoSuchEntityException:
pass # the user had no console password
# deactivate, don't delete, access keys so they can be switched back on
for key in iam_client.list_access_keys(UserName=user_name)["AccessKeyMetadata"]:
iam_client.update_access_key(UserName=user_name, AccessKeyId=key["AccessKeyId"], Status="Inactive")
if __name__ == "__main__":
print(f"π Checking for IAM users inactive for {DAYS_INACTIVE} days...")
unused_users = get_unused_iam_users()
if not unused_users:
print("β
No inactive users found.")
for user_name, last in unused_users:
if DRY_RUN:
print(f"β οΈ Would disable {user_name} (last active {last:%Y-%m-%d})")
else:
disable_user(user_name)
print(f"π Disabled IAM user: {user_name} (last active {last:%Y-%m-%d})")β Challenge 5: Implement a log monitoring system that scans EC2 instances' /var/log for error messages and sends alerts via email (AWS SES) and Slack.
# Step 1: Install Required Packages
# pip install boto3 requests paramiko
import boto3
import paramiko
import requests
AWS_REGION = "us-east-1"
EC2_NAME_TAG = "log-monitor" # watch instances whose Name tag is log-monitor
KEY_FILE = "your-key.pem"
SSH_USERNAME = "ubuntu"
SES_SENDER = "[email protected]" # must be a verified SES identity
SES_RECIPIENT = "[email protected]"
SUBJECT = "π¨ EC2 Log Monitoring Alert"
SLACK_WEBHOOK_URL = "https://hooks.slack.com/services/your/slack/webhook"
# error-level entries from the last hour; most of /var/log is root-only, hence sudo
LOG_CMD = "sudo journalctl -p err --since '-1h' --no-pager -q | tail -n 20"
ec2_client = boto3.client("ec2", region_name=AWS_REGION)
ses_client = boto3.client("ses", region_name=AWS_REGION)
def get_ec2_instances():
response = ec2_client.describe_instances(
Filters=[
{"Name": "tag:Name", "Values": [EC2_NAME_TAG]},
{"Name": "instance-state-name", "Values": ["running"]}
]
)
return [
(instance["InstanceId"], instance["PublicIpAddress"])
for reservation in response["Reservations"]
for instance in reservation["Instances"]
if "PublicIpAddress" in instance
]
def check_logs(instance_ip):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(hostname=instance_ip, username=SSH_USERNAME, key_filename=KEY_FILE, timeout=30)
stdin, stdout, stderr = ssh.exec_command(LOG_CMD)
return stdout.read().decode().strip()
except Exception as e:
print(f"β Failed to connect to {instance_ip}: {e}")
return ""
finally:
ssh.close()
def send_email(subject, body):
try:
ses_client.send_email(
Source=SES_SENDER,
Destination={"ToAddresses": [SES_RECIPIENT]},
Message={"Subject": {"Data": subject}, "Body": {"Text": {"Data": body}}}
)
print("β
Email alert sent!")
except Exception as e:
print(f"β Failed to send email: {e}")
def send_slack_alert(message):
try:
response = requests.post(SLACK_WEBHOOK_URL, json={"text": message}, timeout=10)
response.raise_for_status()
print("β
Slack alert sent!")
except Exception as e:
print(f"β Failed to send Slack message: {e}")
def monitor_ec2_logs():
print("π Checking EC2 logs for errors...")
instances = get_ec2_instances()
if not instances:
print("β οΈ No running instances found with the specified Name tag.")
return
all_errors = []
for instance_id, instance_ip in instances:
output = check_logs(instance_ip)
if output:
all_errors.append(f"π΄ {instance_id} ({instance_ip})\n{output}")
if all_errors:
message_body = "\n\n".join(all_errors)
print(f"π¨ Errors Found:\n{message_body}")
send_email(SUBJECT, message_body)
send_slack_alert(message_body)
else:
print("β
No errors found in logs.")
if __name__ == "__main__":
monitor_ec2_logs()β Challenge 6: Automate DNS record updates in AWS Route 53 using Python.
# Step 1: Create the Python Script (update_route53.py)
import boto3
import requests
AWS_REGION = "us-east-1"
HOSTED_ZONE_ID = "ZXXXXXXXXXXXXX"
DOMAIN_NAME = "example.com"
RECORD_TYPE = "A"
TTL = 300
route53_client = boto3.client("route53", region_name=AWS_REGION)
def update_dns_record(ip_address):
print(f"π Updating DNS record {DOMAIN_NAME} β {ip_address}")
change_batch = {
"Changes": [
{
"Action": "UPSERT",
"ResourceRecordSet": {
"Name": DOMAIN_NAME,
"Type": RECORD_TYPE,
"TTL": TTL,
"ResourceRecords": [{"Value": ip_address}]
}
}
]
}
try:
response = route53_client.change_resource_record_sets(
HostedZoneId=HOSTED_ZONE_ID,
ChangeBatch=change_batch
)
print(f"β
DNS record updated! Change ID: {response['ChangeInfo']['Id']}")
except Exception as e:
print(f"β Failed to update DNS record: {e}")
if __name__ == "__main__":
ip = requests.get("https://api.ipify.org", timeout=10).text.strip() # IPv4 only: an A record needs it
update_dns_record(ip)
β Challenge 7: Write a script that triggers an AWS Lambda function using boto3.
# Step 1: Create the Python Script (trigger_lambda.py)
import boto3
import json
AWS_REGION = "us-east-1"
LAMBDA_FUNCTION_NAME = "my_lambda_function"
lambda_client = boto3.client("lambda", region_name=AWS_REGION)
def invoke_lambda(payload=None):
print(f"π Triggering Lambda function: {LAMBDA_FUNCTION_NAME}")
try:
response = lambda_client.invoke(
FunctionName=LAMBDA_FUNCTION_NAME,
InvocationType="RequestResponse",
Payload=json.dumps(payload or {})
)
response_payload = json.loads(response["Payload"].read().decode())
if "FunctionError" in response: # the call succeeded but the function raised
print(f"β Function error: {response_payload}")
return
print(f"β
Lambda response: {response_payload}")
except Exception as e:
print(f"β Failed to invoke Lambda: {e}")
if __name__ == "__main__":
payload = {"message": "Hello from Python!"}
invoke_lambda(payload)
β Challenge 8: Use boto3 to fetch AWS billing data, and generate a cost analysis report in PDF format
# Step 1: Install packages
# pip install boto3 reportlab
import boto3
from datetime import datetime, timedelta, timezone
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
# Cost Explorer lives in us-east-1 and must be enabled in the Billing console;
# each API request costs $0.01
COST_EXPLORER_CLIENT = boto3.client("ce", region_name="us-east-1")
END_DATE = datetime.now(timezone.utc).date() # End is exclusive: the last 7 full days
START_DATE = END_DATE - timedelta(days=7)
def get_billing_data():
print("π Fetching AWS cost data...")
try:
response = COST_EXPLORER_CLIENT.get_cost_and_usage(
TimePeriod={"Start": START_DATE.strftime("%Y-%m-%d"), "End": END_DATE.strftime("%Y-%m-%d")},
Granularity="DAILY",
Metrics=["UnblendedCost"]
)
return response["ResultsByTime"]
except Exception as e:
print(f"β Failed to fetch billing data: {e}")
return []
def generate_pdf_report(cost_data):
report_filename = f"AWS_Cost_Report_{END_DATE}.pdf"
print(f"π Generating PDF report: {report_filename}")
c = canvas.Canvas(report_filename, pagesize=letter)
c.setFont("Helvetica-Bold", 16)
c.drawString(200, 750, "AWS Billing Report")
c.setFont("Helvetica", 12)
c.drawString(200, 730, f"Time Period: {START_DATE} - {END_DATE}")
y_position = 700
total_cost = 0
for entry in cost_data:
date = entry["TimePeriod"]["Start"]
cost = float(entry["Total"]["UnblendedCost"]["Amount"])
total_cost += cost
c.drawString(100, y_position, f"{date}: ${cost:.2f}")
y_position -= 20
c.setFont("Helvetica-Bold", 14)
c.drawString(100, y_position - 20, f"Total AWS Cost: ${total_cost:.2f}")
c.save()
print(f"β
PDF report saved as {report_filename}")
return report_filename
if __name__ == "__main__":
cost_data = get_billing_data()
if cost_data:
generate_pdf_report(cost_data)Bonus π‘ Send the PDF via Email (AWS SES):
import boto3
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# get_billing_data() and generate_pdf_report() as above
SES_CLIENT = boto3.client("ses", region_name="us-east-1")
def send_email_with_pdf(recipient_email, pdf_filename):
sender_email = "[email protected]" # must be a verified SES identity
msg = MIMEMultipart()
msg["From"] = sender_email
msg["To"] = recipient_email
msg["Subject"] = "AWS Cost Report"
msg.attach(MIMEText("Please find the attached AWS billing report.", "plain"))
with open(pdf_filename, "rb") as attachment:
pdf_part = MIMEApplication(attachment.read(), _subtype="pdf")
pdf_part.add_header("Content-Disposition", "attachment", filename=pdf_filename)
msg.attach(pdf_part)
try:
response = SES_CLIENT.send_raw_email(
Source=sender_email,
Destinations=[recipient_email],
RawMessage={"Data": msg.as_string()},
)
print(f"π§ Report sent to {recipient_email}, Message ID: {response['MessageId']}")
except Exception as e:
print(f"β Failed to send email: {e}")
if __name__ == "__main__":
cost_data = get_billing_data()
if cost_data:
report_file = generate_pdf_report(cost_data)
send_email_with_pdf("[email protected]", report_file)How to Participate?
β
Complete the tasks and challenges.
β
Document your progress and key takeaways on GitHub ReadMe, Medium, or Hashnode.
β
Share the above in a LinkedIn post tagging me (Sandip Das) and use #60DaysDevOps to engage with the community!
#60DaysOfDevOps: Day 6: Advanced Python For DevOps Solutions Updated here
Explore past #60DaysOfDevOps challenges and their solutions here:
Python Basics for DevOps (60 Days of DevOps Challenge Day 5 )
Git Advanced - Rebase, Cherry-pick, Conflict Resolution (60 Days of DevOps Challenge: Day 4)
Git & GitHub - Basics, Branching, Merging, PRs (60 Days DevOps Challenge: Day 3)
Linux Shell Scripting & Automation (60 Days DevOps Challenge: Day 2)
Linux Basics - Commands, File System, Users & Permissions (60 Days DevOps Challenge: Day 1)
You may also like:
- EKS Auto Mode with Terraform is the BEST Way to Manage Amazon EKS
- Want to Understand AI & ML? Start Here!
- MLOps Step 1: Data Extraction, Validation & Preparation for ML Training & ETL Process
β‘ Quick Reference
Keep the momentum going β everything you need on LearnXOps in one place:
- π Courses β Video courses & AI-built courses
- π Ebooks β Community ebooks & your own
- π§ͺ All Labs & Challenges β DevOps, Cloud, SRE & more
- βΈοΈ Kubernetes Labs & Playground β kind clusters, playground & challenges
- π€ AI Agent & Bot Labs β OpenClaw Β· Hermes Β· CrewAI Β· LangGraph Β· MCP

Member discussion