Sub topic 14
Scripting with the CLI
This chapter covers turning one-off AWS CLI commands into reliable shell scripts. It assumes you can run aws commands, have a working profile, and know how --query, --output, pagination, and waiters behave. The examples use Bash, which works in a local terminal and in CloudShell.
Why scripts need extra care
A command you type is watched by you. A script runs without you, so it must decide what to do when a call fails, when a result is empty, or when it runs under the wrong identity. Most scripting mistakes with the CLI come from three sources: output that is formatted for people, exit codes that are ignored, and identity or Region that is assumed instead of stated.
Start with a safe script header
Put strict settings at the top of every script. They make failures visible instead of letting the script continue with bad data.
#!/usr/bin/env bash
set -euo pipefail
export AWS_PROFILE="${AWS_PROFILE:-dev}"
export AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION:-eu-west-1}"
export AWS_PAGER=""
aws sts get-caller-identity --query Arn --output textWhat each line does:
set -eexits when a command fails.set -utreats an unset variable as an error.set -o pipefailmakes a pipeline fail if any stage fails, not only the last one.AWS_PROFILEandAWS_DEFAULT_REGIONpin the identity and Region for every call. The${VAR:-default}form lets the caller override them.AWS_PAGER=""turns off the interactive pager that AWS CLI v2 uses by default. Without this, a script run in a terminal can stop and wait for a keypress.- The
sts get-caller-identitycall prints the ARN the script runs as. It also fails early if credentials are missing or expired.
Exit codes
The CLI returns an exit code that scripts can test. The common values are:
| Code | Meaning |
|---|---|
| 0 | The command succeeded. |
| 1 | A waiter failed, or a service-side operation reported failure (for example, an S3 transfer error). |
| 2 | The command line was invalid, or the CLI could not parse it. |
| 130 | The command was interrupted with Ctrl+C. |
| 252 | The command syntax was invalid. |
| 253 | The environment or configuration is wrong, such as missing credentials. |
| 254 | The service returned an error, such as AccessDenied or a missing resource. |
| 255 | A general failure. |
Check the AWS CLI documentation for your version, because the exact set of codes can differ between commands. In practice, treat zero as success and anything else as failure. Read stderr for the reason.
With set -e the script stops on any non-zero code. When you want to handle a failure yourself, capture the code explicitly:
if ! out=$(aws s3api head-bucket --bucket amzn-s3-demo-bucket 2>&1); then
echo "Bucket check failed: $out" >&2
exit 1
fiPutting the command inside if ! stops set -e from aborting at that line, so you can print your own message first.
Choose output formats for machines
Use --output text or --output json in scripts. The table format is for reading and changes between releases, so do not parse it.
--output text with --query is the simplest way to put a single value in a variable:
bucket_count=$(aws s3api list-buckets --query 'length(Buckets)' --output text)
echo "Buckets: $bucket_count"A few gotchas apply to text output:
- A query that matches nothing prints
None, not an empty string. Test for it, or use--output jsonand check fornull. - A list of values prints on one line separated by tabs. A list of lists prints one inner list per line. A
[]projection flattens to one line, which is why theforloop shown in the topic examples works. - Values that contain tabs or newlines are not safe in text output. For free-form fields such as tags or descriptions, use JSON.
Use jq for complex JSON
JMESPath inside --query handles most filtering. When you need to join fields into custom text, compute values, or feed output into other tools, pipe JSON to jq:
aws ec2 describe-instances \
--filters "Name=instance-state-name,Values=running" \
--output json |
jq -r '.Reservations[].Instances[] | [.InstanceId, .InstanceType] | @tsv'jq is not part of the CLI and may not be installed. CloudShell includes it. On your own machine, install it with your package manager. Keep --filters in the command so the service does the narrowing and less data crosses the network.
Loop over resources safely
A common pattern is to list identifiers and act on each one. Read the lines with while read instead of an unquoted for, so spaces in names do not split values:
aws ec2 describe-instances \
--filters "Name=instance-state-name,Values=running" \
--query 'Reservations[].Instances[].InstanceId' \
--output text | tr '\t' '\n' |
while read -r id; do
[ -z "$id" ] && continue
echo "Tagging $id"
aws ec2 create-tags --resources "$id" --tags Key=reviewed,Value=true
doneTwo details matter here. tr '\t' '\n' converts tab-separated output to one ID per line. The [ -z "$id" ] check skips blank lines, which appear when nothing matches.
Where an API accepts many identifiers in one call, pass them together instead of looping. Here --resources could take all IDs at once, which makes fewer requests and is less likely to be throttled.
Pagination in scripts
Many list calls return one page at a time. By default the CLI follows every page for you and combines them into one result, so --query applies to the full set. Two options change this:
--max-itemscaps the total number of items returned. If more exist, the output includes aNextToken, and you pass its value to--starting-tokento resume.--page-sizesets how many items each underlying request fetches. A smaller page size helps when a large page makes a call time out.
When a script processes very large lists, do not set --max-items unless you also handle NextToken. A cap with no follow-up silently drops items.
Waiters instead of sleep
Many operations are asynchronous. The API returns before the resource is ready. Avoid sleep 60 guesses and use a waiter, which polls until a state is reached or a timeout expires:
id=$(aws ec2 run-instances \
--image-id ami-0123456789abcdef0 \
--instance-type t3.micro \
--query 'Instances[0].InstanceId' \
--output text)
aws ec2 wait instance-running --instance-ids "$id"
echo "$id is running"If the waiter times out, it exits with code 1, so set -e stops the script. Waiters have fixed polling intervals and attempt limits that you cannot change from the command line. For longer waits, call the matching describe operation in your own loop.
Dry runs and confirmation
Run destructive or bulk commands in a preview mode first:
aws s3 sync ... --dryrunandaws s3 rm ... --dryrunlist what would change.- Many EC2 commands accept
--dry-run. The call does not make the change. It returns an error namedDryRunOperationwhen you have permission, andUnauthorizedOperationwhen you do not.
A script can expose this as a switch:
#!/usr/bin/env bash
set -euo pipefail
DRY=""
[ "${1:-}" = "--apply" ] || DRY="--dryrun"
aws s3 sync ./site s3://amzn-s3-demo-bucket $DRYHere the script previews by default, and a person has to pass --apply to make changes. The unquoted $DRY is deliberate, because an empty value must disappear from the command.
Handling throttling and retries
The CLI retries throttled and transient errors automatically. You can tune this with the AWS_RETRY_MODE and AWS_MAX_ATTEMPTS environment variables, or retry_mode and max_attempts in the profile. The standard mode is the usual choice, and adaptive adds client-side rate limiting. Raise AWS_MAX_ATTEMPTS before adding your own retry loops.
export AWS_RETRY_MODE=standard
export AWS_MAX_ATTEMPTS=8Credentials in scripts
Scripts should not contain access keys. Use the identity already configured:
- On your machine, rely on a named profile, and for IAM Identity Center, run
aws sso loginbefore the script. The script fails with an expiry error if the session has lapsed, so do not try to log in from inside it. - In CloudShell, the CLI uses the credentials of the signed-in Console user, so no setup is needed.
- On AWS compute, such as EC2 or Lambda, use the attached role.
Never print credentials or pass them on the command line, where other users on the machine can see them in the process list. Do not use set -x in scripts that handle secrets, because it echoes expanded commands to the log.
Looping across Regions
The --region option overrides the default for one call, which lets a script cover several Regions:
for r in $(aws ec2 describe-regions --query 'Regions[].RegionName' --output text); do
echo "$r: $(aws ec2 describe-vpcs --region "$r" --query 'length(Vpcs)' --output text)"
doneThis runs one call per enabled Region and runs serially. Disabled opt-in Regions are not returned by describe-regions by default, so they are skipped.
Common mistakes
- Parsing
tableoutput, which breaks when formatting changes. - Forgetting that an empty text result prints
None. - Using
--max-itemswith noNextTokenhandling. - Leaving the pager on, so an unattended script hangs.
- Running with the wrong profile because
AWS_PROFILEwas set in an earlier shell session. - Quoting
--queryexpressions with double quotes, so the shell expands backticks and$. Use single quotes around the whole expression.
Exercise
A script runs ids=$(aws ec2 describe-instances --filters "Name=tag:env,Values=test" --query 'Reservations[].Instances[].InstanceId' --output text) and then loops over $ids to stop each instance. On a day when no test instances exist, it tries to stop an instance called None and fails. What causes this, and how do you fix it?
Show answer
With --output text, a query that returns no matches prints the word None, which the loop treats as an ID. Fix it by checking for it before looping, for example [ "$ids" = "None" ] || [ -z "$ids" ] && exit 0. Alternatively, request --output json, parse the list with jq -r '.[]', which prints nothing for an empty list. Also pass all IDs to one stop-instances call where possible.
Exercise
Why should a deployment script that is run unattended set AWS_PAGER="" and start with aws sts get-caller-identity?
Show answer
Setting AWS_PAGER="" stops AWS CLI v2 from opening its pager, which would block the script waiting for input. The sts get-caller-identity call confirms the script is running as the intended identity and fails early if credentials are missing or expired, before any change is made.