Use boto3 to rotate through all regions and count running instances in each.
IntermediateHands-onPython for DevOps
Answer
import boto3
regions = [r["RegionName"] for r in boto3.client("ec2", region_name="us-east-1").describe_regions()["Regions"]]
for region in regions:
ec2 = boto3.client("ec2", region_name=region)
n = sum(
len(res["Instances"])
for page in ec2.get_paginator("describe_instances").paginate(
Filters=[{"Name": "instance-state-name", "Values": ["running"]}])
for res in page["Reservations"]
)
if n:
print(f"{region}: {n}")
Key trick → describe_regions returns only regions enabled for the account (opt-in regions excluded unless enabled), so you won't get auth errors from disabled regions.
More on Python for DevOps
Write a Python script using boto3 that lists all running EC2 instances with their Name tag.BeginnerWrite a script that finds unattached EBS volumes and deletes them (with a dry-run flag).IntermediateCall a REST API with `requests`, handle timeouts and non-2xx responses properly.BeginnerAdd retry with exponential backoff to HTTP calls without writing the loop yourself.IntermediateWrite your own retry decorator with exponential backoff and jitter.AdvancedParse a YAML file and print every container image in a multi-document Kubernetes manifest.Intermediate