Sub topic 14
Scripting with the CLI
This chapter assumes you can run aws commands, have a working profile, and know how --query and --output behave. It covers how to turn those commands into shell scripts that behave predictably when no one is watching.
Why scripts need extra care
At a terminal you read each result and react. A script can't. It must pick the identity and Region itself, get output it can parse, and stop when something fails. Most scripting bugs come from leaving one of these to chance.
Make the environment explicit
Pass --profile and --region on every call, or set AWS_PROFILE and AWS_DEFAULT_REGION once at the top. Don't rely on whatever your shell happens to have. Also disable the pager. AWS CLI v2 sends long output to a pager such as less, which makes a script wait for a key press. Setting AWS_PAGER="" turns it off.
Get output you can parse
Use --output text with a --query that returns one value per line or one scalar. Use --output json when you need structure, and pass it to a JSON tool such as jq. Always quote the --query expression in single quotes so the shell does not expand characters like [ and *.
This script counts VPCs in every enabled Region:
#!/usr/bin/env bash
set -euo pipefail
export AWS_PAGER=""
profile="${1:-dev}"
for r in $(aws ec2 describe-regions --profile "$profile" \
--query 'Regions[].RegionName' --output text); do
count=$(aws ec2 describe-vpcs --profile "$profile" --region "$r" \
--query 'length(Vpcs)' --output text)
echo "$r: $count"
doneset -e stops the script on the first failing command. -u treats an unset variable as an error. -o pipefail makes a pipeline fail if any stage fails, not only the last one.
Check exit codes
The CLI returns an exit code that scripts can test.
| Code | Meaning |
|---|---|
| 0 | Command succeeded |
| 252 | Invalid command or parameters |
| 253 | Configuration or credentials problem |
| 254 | The service returned an error |
| 255 | Other failure, including a waiter timing out |
With set -e you get the stop-on-failure behavior for free. To handle a failure yourself, test the command directly: if ! aws sts get-caller-identity >/dev/null; then ... fi. This is a cheap first line for any script, because it fails early when credentials have expired.
Combine with pagination, waiters, and dry runs
List commands page automatically in a script, so you get the full result unless you set --max-items. A waiter such as aws ec2 wait instance-running blocks until a state is reached, which replaces a hand-written sleep loop. Before any bulk change, preview it:
aws s3 sync ./site s3://amzn-s3-demo-bucket --dryrunCommon errors
- Empty results print
Nonein text output. Check for that value before using the result. - Multiple fields in text output are tab-separated. A value with spaces can split into several loop items. Select one field per command, or use JSON with
jq. - The script works in your shell but fails in cron or CI. The environment there has no
AWS_PROFILEand no SSO session. Pass the profile explicitly and use credentials that suit unattended runs. - Expired SSO login. Run
aws sso loginbefore long scripts, and avoid putting long-lived access keys in script files.
Exercise
A script loops over aws ec2 describe-instances --query 'Reservations[].Instances[].[InstanceId,Tags[0].Value]' --output text and sometimes processes the wrong values. Why, and how do you fix it?
Show answer
Text output separates the two fields with a tab, and an instance with no tags prints None, so the loop splits on whitespace and misaligns the values. Fix it by selecting one field per command, or by using --output json and parsing with jq so each record stays intact and missing tags can be handled.