AWS CLI and SDK (boto3)
Everything in the console can be automated. The AWS CLI is the tool for the terminal and shell scripts; the SDKs (boto3 for Python, and SDKs for JavaScript, Java, Go, .NET, Rust and more) are for application code. Both sign requests with your credentials and call the same HTTPS APIs.
AWS CLI essentials
aws --version
aws configure sso # sign in with IAM Identity Center (recommended)
aws s3 ls --profile learner --region eu-west-1
aws ec2 describe-instances \
--filters Name=instance-state-name,Values=running \
--query "Reservations[].Instances[].{id:InstanceId,type:InstanceType,az:Placement.AvailabilityZone}" \
--output tableSample output:
-------------------------------------------------------
| DescribeInstances |
+-------------+------------------------+--------------+
| az | id | type |
+-------------+------------------------+--------------+
| eu-west-1a | i-0f1e2d3c4b5a69788 | t3.micro |
| eu-west-1b | i-0a9b8c7d6e5f43210 | m7g.large |
+-------------+------------------------+--------------+Useful options:
| Option | Effect |
|---|---|
--query |
Filter and reshape output with JMESPath (client side) |
--filters |
Filter on the server side (fewer results transferred) |
--output json|table|text|yaml |
Output format; text is handy in shell scripts |
--profile, --region |
Choose credentials and Region |
--dry-run |
Check permissions without making changes (EC2) |
--no-cli-pager |
Print without a pager, for scripts |
Model: what --query does
--query uses JMESPath expressions. A tiny subset of it, implemented in Python, shows what an expression like Reservations[].Instances[].InstanceId does to the JSON response:
response = {
"Reservations": [
{"Instances": [{"InstanceId": "i-0aaa", "InstanceType": "t3.micro", "State": {"Name": "running"}}]},
{"Instances": [{"InstanceId": "i-0bbb", "InstanceType": "m7g.large", "State": {"Name": "stopped"}},
{"InstanceId": "i-0ccc", "InstanceType": "t3.micro", "State": {"Name": "running"}}]},
]
}
def query(data, expression):
current = [data]
for part in expression.split("."):
flatten = part.endswith("[]")
key = part[:-2] if flatten else part
nxt = []
for item in current:
value = item.get(key) if isinstance(item, dict) else None
if value is None:
continue
if flatten:
nxt.extend(value)
else:
nxt.append(value)
current = nxt
return current
print(query(response, "Reservations[].Instances[].InstanceId"))
print(query(response, "Reservations[].Instances[].State.Name"))
types = query(response, "Reservations[].Instances[].InstanceType")
print({t: types.count(t) for t in sorted(set(types))})['i-0aaa', 'i-0bbb', 'i-0ccc']
['running', 'stopped', 'running']
{'m7g.large': 1, 't3.micro': 2}
boto3
import boto3
session = boto3.Session(profile_name="learner", region_name="eu-west-1")
ec2 = session.client("ec2")
paginator = ec2.get_paginator("describe_instances")
for page in paginator.paginate(Filters=[{"Name": "instance-state-name", "Values": ["running"]}]):
for reservation in page["Reservations"]:
for inst in reservation["Instances"]:
print(inst["InstanceId"], inst["InstanceType"])Key ideas:
- Clients (
boto3.client("s3")) map one-to-one to API operations and return dictionaries. (Resources, the older object-oriented interface, are no longer getting new features.) - Paginators: list calls return at most a page of results with a
NextToken; paginators loop for you. - Waiters:
ec2.get_waiter("instance_running").wait(InstanceIds=[...])polls until a state is reached. - Errors: catch
botocore.exceptions.ClientErrorand inspecte.response["Error"]["Code"].
Model: pagination
ALL_KEYS = [f"logs/day-{n:02d}.gz" for n in range(1, 12)]
def list_objects_page(token=None, max_keys=4):
"""Fake API: returns one page and a NextToken, like S3 ListObjectsV2."""
start = int(token) if token else 0
page = ALL_KEYS[start:start + max_keys]
nxt = str(start + max_keys) if start + max_keys < len(ALL_KEYS) else None
return {"Contents": page, "NextContinuationToken": nxt}
def paginate():
token, pages = None, 0
while True:
resp = list_objects_page(token)
pages += 1
yield from resp["Contents"]
token = resp["NextContinuationToken"]
if token is None:
print(f"(fetched {pages} pages)")
return
items = list(paginate())
print(len(items), "items:", items[0], "...", items[-1])(fetched 3 pages)
11 items: logs/day-01.gz ... logs/day-11.gz
A classic bug is forgetting pagination: the script works in a test account with 20 resources and silently misses most of them in production.
Model: retries with exponential backoff
AWS APIs throttle busy callers (ThrottlingException, HTTP 429/503). The SDKs retry automatically with exponential backoff and jitter. This model shows the delays of the "full jitter" strategy, using a seeded generator so the output is repeatable:
import random
rng = random.Random(7) # seeded: same delays every run
BASE, CAP = 0.1, 5.0
def backoff_delays(attempts):
for attempt in range(attempts):
ceiling = min(CAP, BASE * 2 ** attempt)
yield attempt + 1, ceiling, rng.uniform(0, ceiling)
for attempt, ceiling, delay in backoff_delays(7):
print(f"retry {attempt}: wait up to {ceiling:4.1f} s -> sleeping {delay:.2f} s")retry 1: wait up to 0.1 s -> sleeping 0.03 s
retry 2: wait up to 0.2 s -> sleeping 0.03 s
retry 3: wait up to 0.4 s -> sleeping 0.26 s
retry 4: wait up to 0.8 s -> sleeping 0.06 s
retry 5: wait up to 1.6 s -> sleeping 0.86 s
retry 6: wait up to 3.2 s -> sleeping 1.17 s
retry 7: wait up to 5.0 s -> sleeping 0.29 s
The ceiling doubles each time (up to a cap), and the jitter spreads retries out so thousands of clients don't all retry at the same instant. In boto3 you configure it with botocore.config.Config(retries={"mode": "standard", "max_attempts": 5}).
Test yourself
What is the difference between --filters and --query in the AWS CLI?
- None
--filtersfilters on the server;--queryreshapes the output on the client--queryis faster--filtersis only for S3
Why should you use a paginator in boto3 for list operations?
- It encrypts results
- List APIs return results in pages; the paginator follows the tokens for you
- It is required for S3 only
- It makes calls cheaper
Why add jitter to exponential backoff?
- To make retries faster
- So that many clients don't retry at exactly the same moment
- To avoid using credentials
- AWS requires it for signing