Automating AWS with boto3
Write Python scripts that audit and clean up AWS resources.
By Invicly Tech, , in Full DevOps with Python. About 12 minutes to read.
In short
boto3 is the AWS SDK for Python. It lets you script audits and clean-ups, such as finding untagged instances, with real error handling and a dry-run mode before anything is deleted.
Explained simply
boto3 is the official Python library for AWS. Anything you can click in the console or type with the aws CLI, you can do from a Python script. That makes it the tool of choice for audits, reports and clean-ups that would be slow and error-prone by hand.
You never put keys in the script. boto3 looks for credentials by itself: in environment variables, in your ~/.aws files, or in the IAM role of the machine it runs on. The same script works on your laptop and on a server without changes.
AWS answers list requests in pages, often 50 to 1,000 items at a time. If your script reads only the first page, it silently misses the rest. Paginators fetch every page for you.
Things go wrong: missing permissions, a resource that no longer exists, too many requests at once. boto3 raises an exception called ClientError with an error code you can check and handle.
A clean-up script can delete real resources, so build it to be safe. By default it should only print what it would do. It acts only when you pass a clear flag like --apply, and it should skip anything tagged as protected.
Press Play on a diagram to walk through it one step at a time.
- 1Create session
Pick profile and region; credentials come from the default chain.
- 2Create client
boto3 client for ec2, s3 or another service.
- 3Paginate results
Paginators fetch every page, not just the first.
- 4Filter candidates
Untagged, stopped or idle resources.
- 5Report in dry run
Print what would change; default to no action.
- 6Act with --apply
Only then stop or delete, with logging.
- Holds profile, region, credentials
- One per account or region you target
- Not thread-safe
- One method per API call
- Returns plain dicts
- Has paginators and waiters
- Recommended for new code
- Object style, like bucket.objects
- Older layer, no new features
- Handy for simple S3 and EC2 scripts
In depth
Where boto3 finds credentials and region
boto3 walks a chain of credential providers and uses the first one that returns keys. In order: values passed directly to Session or client (avoid this), the environment variables AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN, then providers driven by your profile and environment (role_arn to assume a role, a web identity token as used by EKS pods and CI, an IAM Identity Center profile, and the shared files ~/.aws/credentials and ~/.aws/config), the container credentials endpoint (ECS tasks), and finally the EC2 instance metadata service.
The profile comes from profile_name= or the AWS_PROFILE variable. The region comes from region_name=, AWS_REGION or AWS_DEFAULT_REGION, or the profile's region setting. Many "it works on my laptop" bugs are a different profile or region, so print sts get_caller_identity() and session.region_name at the start of every audit script.
For IAM Identity Center profiles, run aws sso login first; boto3 then reads the cached token and refreshes role credentials automatically.
- 1Explicit arguments
Keys passed in code; avoid
- 2Environment variables
AWS_ACCESS_KEY_ID and friends
- 3Profile providers
role_arn, web identity, SSO
- 4~/.aws files
Keys in credentials or config
- 5Container endpoint
ECS task role
- 6Instance metadata
EC2 instance role via IMDS
Sessions, clients and resources
A Session holds a credential source, a profile and a region. boto3.client("ec2") quietly uses a default session; creating your own with boto3.Session(profile_name=..., region_name=...) makes scripts explicit and lets you work with several accounts or regions at once.
A client maps one to one to the AWS API: describe_instances is the DescribeInstances call, and it returns a plain dict that includes ResponseMetadata. Method names are the API names in snake_case, and the boto3 docs list every parameter and response field.
Resources (boto3.resource("s3")) are an older, object-style layer: bucket.objects.all() and so on. They still work, but the boto3 team stopped adding features to them, so new services and new API fields appear only in clients. Prefer clients for new code.
Clients are generally safe to share across threads; Session objects are not, so create one session per thread when you parallelise. Most services are regional: an EC2 client sees only its own region, so an account-wide audit loops over regions.
- ec2.describe_regions() returns the regions enabled for the account
- S3 list_buckets is global, but each bucket lives in one region
- Use botocore.config.Config to set retries and timeouts
Pagination and server-side filters
List APIs return a page plus a token for the next one. The name of the token differs by service: NextToken for EC2, ContinuationToken for S3 list_objects_v2, Marker for some older APIs. A paginator hides these details: client.get_paginator("describe_instances").paginate() yields every page until there is no token left.
You can tune it with PaginationConfig={"PageSize": 100, "MaxItems": 500}, and you can flatten results with JMESPath: pages.search("Reservations[].Instances[]") yields instances one at a time.
Filter on the server when the API supports it. describe_instances accepts Filters such as instance-state-name=stopped or tag-key=owner, and describe_volumes accepts status=available. This sends less data and makes fewer calls than downloading everything and filtering in Python. Not every API has a paginator; client.can_paginate("name") tells you.
- Your loop to Paginator: for page in paginate()1for page in paginate()
- Paginator to EC2 API: DescribeInstances2DescribeInstances
- EC2 API to Paginator: Page 1 + NextToken3Page 1 + NextToken
- Paginator to Your loop: Yield page 14Yield page 1
- Paginator to EC2 API: DescribeInstances with NextToken5DescribeInstances with NextToken
- EC2 API to Paginator: Last page, no token6Last page, no token
- Paginator to Your loop: Yield last page, loop ends7Yield last page, loop ends
Errors, retries, waiters and EC2 DryRun
Service errors raise botocore.exceptions.ClientError. Read e.response["Error"]["Code"] to decide what to do: S3 uses codes like NoSuchBucket and AccessDenied, EC2 uses UnauthorizedOperation and InvalidInstanceID.NotFound. Problems before the call raise other botocore exceptions, such as NoCredentialsError. For common S3 errors, client.exceptions.NoSuchKey also works in except clauses.
boto3 retries throttling and temporary errors for you. Set the behaviour explicitly with Config(retries={"max_attempts": 10, "mode": "standard"}); adaptive mode also slows the client down when AWS throttles. Do not wrap calls in your own tight retry loops.
Waiters poll until a resource reaches a state: ec2.get_waiter("instance_stopped").wait(InstanceIds=[...]). Many EC2 calls also take DryRun=True. AWS checks permissions without doing anything and raises ClientError with code DryRunOperation if you would have been allowed, or UnauthorizedOperation if not. It is a useful permission test, but it is not a replacement for your script's own dry-run mode.
- Catch specific codes; re-raise anything you did not expect
- Log the resource ID with every error
- Throttling shows up as codes like Throttling or RequestLimitExceeded
Finding waste and cleaning up safely
Good first targets: instances with no owner tag, instances stopped for weeks (their EBS volumes still cost money), EBS volumes in the available state (attached to nothing), Elastic IPs with no association (AWS now charges for every public IPv4 address), old snapshots, and S3 buckets with no lifecycle rules. For "idle", read CloudWatch: an instance whose CPUUtilization stayed under a few percent for 14 days is a candidate to stop or downsize.
The Resource Groups Tagging API (get_resources) is handy across services, but it returns only resources that have or once had tags, so it cannot find things that were never tagged. Use each service's describe call for that.
Design for safety: dry run by default, an explicit --apply flag, an allowlist tag like keep=true that is always skipped, a clear log of every action, and a least-privilege role for the script. Many teams tag first (marked-for-deletion with a date), notify the owner, and delete a week later.
- 1Scan
Find untagged or idle resources
- 2Tag
Add marked-for-deletion with a date
- 3Notify
Post the list to the team channel
- 4Wait
Give owners a week to object
- 5Delete with --apply
Skip anything tagged keep=true
- Back to step 1
Learn it in 5 short steps
About 1h each. Track them with a timer in your plan.
- 1Configure credentials and sessions~1h
- 2List EC2 instances and S3 buckets~1h
- 3Handle pagination and errors~1h
- 4Find untagged or idle resources~1h
- 5Write a dry-run clean-up script~1h
Key points
- Credentials come from env vars, ~/.aws files or an attached IAM role, in that order.
- List APIs return pages; use get_paginator so large accounts are fully covered.
- Catch botocore ClientError and read the error code to handle failures clearly.
- Make dry run the default so a mistake only prints, never deletes.
Key terms
Tap a card to flip it. 0/5 known
Examples
import boto3
from botocore.exceptions import ClientError
session = boto3.Session(profile_name="dev", region_name="us-east-1")
ec2 = session.client("ec2")
pages = ec2.get_paginator("describe_instances").paginate()
for page in pages:
for res in page["Reservations"]:
for inst in res["Instances"]:
tags = {t["Key"]: t["Value"] for t in inst.get("Tags", [])}
if "owner" not in tags:
print("DRY RUN would stop", inst["InstanceId"])
try:
ec2.describe_instances(InstanceIds=["i-doesnotexist"])
except ClientError as e:
print("Error:", e.response["Error"]["Code"])Find instances missing an owner tag, safely.
Report every S3 bucket with its region and lifecycle status
Step 1: list buckets; this call is global. Step 2: for each bucket, ask for its location. The API returns None for us-east-1, a historical quirk you must handle. Step 3: ask for its lifecycle configuration; a bucket without rules raises ClientError with code NoSuchLifecycleConfiguration, which is the case you want to report. Step 4: any other error, such as AccessDenied, is printed instead of crashing the whole report.
import boto3
from botocore.exceptions import ClientError
s3 = boto3.client("s3")
for b in s3.list_buckets()["Buckets"]:
name = b["Name"]
region = s3.get_bucket_location(Bucket=name)["LocationConstraint"] or "us-east-1"
try:
rules = s3.get_bucket_lifecycle_configuration(Bucket=name)["Rules"]
status = f"{len(rules)} lifecycle rules"
except ClientError as e:
code = e.response["Error"]["Code"]
status = "NO LIFECYCLE" if code == "NoSuchLifecycleConfiguration" else f"error: {code}"
print(f"{name:40} {region:15} {status}")Dry-run clean-up of unattached EBS volumes
Step 1: parse an --apply flag; without it the script only reports. Step 2: paginate describe_volumes with a server-side filter for status available, which means attached to nothing. Step 3: build a tag dict and skip volumes tagged keep=true. Step 4: print each candidate with its size, so the report shows the money at stake. Step 5: only with --apply, call delete_volume. Run it in each region you use, and keep a copy of the output.
import argparse, boto3
ap = argparse.ArgumentParser()
ap.add_argument("--apply", action="store_true")
ap.add_argument("--region", default="us-east-1")
args = ap.parse_args()
ec2 = boto3.Session(region_name=args.region).client("ec2")
pages = ec2.get_paginator("describe_volumes").paginate(
Filters=[{"Name": "status", "Values": ["available"]}])
for vol in pages.search("Volumes[]"):
tags = {t["Key"]: t["Value"] for t in vol.get("Tags", [])}
if tags.get("keep") == "true":
continue
print("DELETE" if args.apply else "WOULD DELETE", vol["VolumeId"], f'{vol["Size"]} GiB')
if args.apply:
ec2.delete_volume(VolumeId=vol["VolumeId"])Quick reference
- boto3.Session(profile_name="dev", region_name="eu-west-1").client("ec2") makes scripts explicit
- boto3.client("sts").get_caller_identity()["Arn"] shows which identity the script uses
- client.get_paginator("op").paginate().search("JMESPath") yields items across all pages
- Catch ClientError and read e.response["Error"]["Code"]
- Config(retries={"max_attempts": 10, "mode": "standard"}) sets retry behaviour
- ec2.get_waiter("instance_running").wait(InstanceIds=[...]) blocks until the state is reached
- EC2 DryRun=True raises DryRunOperation if you would be allowed
- get_bucket_location returns None for buckets in us-east-1
Common mistakes
- Reading only the first page of results and missing most resources.
- Hard-coding access keys in the script instead of using profiles or roles.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a script that prints the account ID, the caller ARN and the region the default session will use.
- Exercise 2medium
Count EC2 instances by state in every enabled region of the account.
- Exercise 3hard
Write a dry-run-by-default script that releases Elastic IPs not associated with anything, skips keep=true, and handles errors per address.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between boto3 and botocore?
- botocore is the low-level library that signs requests, handles retries and knows every API from JSON models. boto3 is built on top of it and adds sessions, resources and a friendlier interface; you import exceptions and Config from botocore.
- boto3 client or resource: which should I use?
- Use clients for new code. They cover every API and new feature, while resources are no longer being extended.
- How do I test boto3 code without touching real AWS?
- Use moto, which mocks AWS services in memory, or botocore's Stubber to queue fake responses. Both run in pytest with no AWS account.
- Why does my script say NoRegionError?
- Most clients need a region and none was found. Pass region_name, set AWS_REGION or AWS_DEFAULT_REGION, or add region to your profile in ~/.aws/config.