Sub topic 7
Anatomy of an AWS CLI command
This chapter assumes you have installed AWS CLI v2 and set up at least one profile, as covered in the earlier chapters on installation and credentials. You should be comfortable with shell quoting and basic JSON. Here you will learn how a command is built, how to find the right command without leaving the terminal, and how the options that apply to every command behave.
The basic shape
Every AWS CLI command follows one pattern:
aws <service> <operation> [options and parameters]The aws program is the entry point. The first word after it is the service, such as ec2, s3api, iam, or sts. The second word is the operation, written in lowercase with hyphens. The remaining words are options, which start with --, and their values.
aws ec2 describe-instances --region eu-west-1 --profile dev --output tableThis command reads as follows: call the DescribeInstances operation of the EC2 service, in the eu-west-1 Region, using the credentials of the dev profile, and print the result as a table.
Operation names map directly to API actions. The CLI converts the API's CamelCase name (DescribeInstances) to lowercase with hyphens (describe-instances). That mapping lets you move between the CLI, the API reference, and IAM policy actions such as ec2:DescribeInstances without guessing.
High-level and low-level commands
Some services have two layers of commands. Amazon S3 is the main example.
aws s3apimirrors the S3 API one operation at a time, for examplelist-buckets,get-object, andput-bucket-policy.aws s3offers hand-written commands such asls,cp,mv,rm, andsync. These commands add behavior the API does not have, such as recursive copies, parallel multipart transfers, and directory synchronization.
Use s3 for moving files and s3api when you need a specific API feature. Most other services have only the one-to-one layer.
Finding commands with built-in help
You do not need a browser to discover commands. Add help at any level:
aws help
aws ec2 help
aws ec2 describe-instances helpThe first lists all services. The second lists the operations of one service. The third shows the full manual page for an operation: a synopsis, every option with its type, and examples. Help opens in your pager, so press q to leave. Press / followed by a word to search inside the page.
To see the available services or operations as plain text, pass an invalid or incomplete command. For example, aws ec2 with no operation prints a usage message and an error listing the valid choices. That output is also a quick way to confirm you spelled a service name correctly.
If the output of a command opens in a pager and interrupts a script, pass --no-cli-pager or set AWS_PAGER="".
Global options
Some options work on every command. The ones you will use most are:
| Option | Purpose |
|---|---|
| `--profile` | Choose a named profile for credentials and defaults |
| `--region` | Choose the Region the request goes to |
| `--output` | Choose `json`, `yaml`, `yaml-stream`, `text`, or `table` |
| `--query` | Filter the result on the client with JMESPath |
| `--no-paginate` | Turn off automatic pagination |
| `--endpoint-url` | Send the request to a different endpoint, such as a local test server |
| `--debug` | Print the full request flow, including which credentials were resolved |
A global option can appear anywhere after aws, but placing it at the end keeps commands easy to read. The next chapter covers --output and --query in detail.
Where settings come from
The same setting, such as the Region, can be defined in several places. The CLI picks the first one it finds in this order, from highest to lowest priority:
- A command-line option, such as
--region eu-west-1. - An environment variable, such as
AWS_REGION,AWS_DEFAULT_REGION, orAWS_PROFILE. - The selected profile in
~/.aws/configand~/.aws/credentials. - For some settings, a built-in default or metadata from the compute environment.
This ordering explains many surprises. If AWS_PROFILE=prod is exported in your shell, every command uses prod unless you pass --profile. If you pass --region, it wins even when the profile sets a different Region.
Check the effective values with:
aws configure list --profile devThe output shows each value and its source (env, config-file, manual, and so on). That column tells you which of the four places supplied the value.
aws sts get-caller-identity --profile devThe sts get-caller-identity command needs no permissions and shows the account ID and ARN the CLI is acting as. Run it before any change you cannot easily undo.
Passing parameters
Parameters take several forms, depending on their type.
Strings and numbers are plain values. Quote any value that contains spaces or shell characters:
aws ec2 describe-instances --instance-ids i-0123456789abcdef0Lists are space-separated values after a single option:
aws ec2 describe-instances \
--instance-ids i-0123456789abcdef0 i-0fedcba9876543210Structures can be written in shorthand syntax, which uses key=value pairs, commas, and braces:
aws ec2 create-tags \
--resources i-0123456789abcdef0 \
--tags Key=Name,Value=web-1JSON works for any structured parameter. Single-quote it in Bash so the shell leaves the double quotes alone:
aws ec2 create-tags \
--resources i-0123456789abcdef0 \
--tags '[{"Key":"Name","Value":"web-1"},{"Key":"Env","Value":"dev"}]'Files are loaded with the file:// prefix. The CLI reads the file and uses its contents as the value:
aws iam create-policy \
--policy-name ReadOnlyLogs \
--policy-document file://policy.jsonUse fileb:// for binary content, such as a ZIP file for Lambda.
Boolean flags take no value. Many have a negative form that starts with --no-, for example --paginate and --no-paginate, or --dry-run for EC2 actions.
Generating input from a skeleton
For operations with many parameters, let the CLI write a template for you:
aws ec2 create-tags --generate-cli-skeleton input > tags.jsonEdit tags.json, then run the command with the file:
aws ec2 create-tags --cli-input-json file://tags.jsonYou can combine --cli-input-json with command-line options. Options typed on the command line override the matching values in the file.
Testing before you change anything
Several tools let you check a command before it acts.
- EC2 and some other services support
--dry-run. The service checks permissions and parameters but does not perform the action. aws s3 cp,mv,rm, andsyncsupport--dryrun, which prints what would happen. The spelling differs between the two commands, so check the help page.- Read-only operations (
describe-*,list-*,get-*) are safe to run to confirm that your profile, Region, and parameters are correct.
With --dry-run, success looks like an error:
aws ec2 create-tags --resources i-0123456789abcdef0 \
--tags Key=Name,Value=web-1 --dry-runThe response is DryRunOperation: Request would have succeeded, but DryRun flag is set. A permission problem returns UnauthorizedOperation instead.
Exit codes
The CLI sets an exit code that scripts can test with $?:
| Code | Meaning |
|---|---|
| 0 | The command succeeded |
| 252 | Invalid command syntax or a missing parameter |
| 253 | A problem with the configuration or credentials |
| 254 | The command was valid, but the service returned an error |
| 255 | A general failure |
Exit code 1 and 2 appear for some commands, such as aws s3 transfers, where code 1 means one or more transfers failed. Use the code to separate your own mistakes (252 and 253) from service-side rejections (254).
Common mistakes
- Wrong Region. An empty result often means you queried a Region where the resources do not exist. Add
--regionor checkaws configure list. - Forgotten environment variable. A stale
AWS_PROFILEorAWS_ACCESS_KEY_IDoverrides the profile you expected. - Misspelled operation. The operation name uses hyphens, not CamelCase:
describe-instances, notDescribeInstances. - Unquoted JSON. The shell strips the double quotes, and the CLI reports a parse error with exit code 252.
- Mixing
s3ands3apioptions. Each has its own parameters. Checkaws s3 helporaws s3api help.
Exercise
You run aws ec2 describe-instances --region us-west-2 in a shell where AWS_PROFILE=prod is exported and ~/.aws/config sets region = eu-west-1 for the prod profile. Which profile and which Region does the command use, and how can you confirm it?
Show answer
It uses the prod profile because the environment variable supplies the profile and no --profile option overrides it. It uses us-west-2 because a command-line option has the highest priority, above the Region in the profile. You can confirm both with aws configure list --region us-west-2, which shows each value and its source, and aws sts get-caller-identity to show the account and identity the credentials resolve to.
Exercise
You want to apply the tags Name=web-1 and Env=dev to an EC2 instance, but you are not sure your permissions allow it. Write a command that checks this without changing the instance, and say what a successful result looks like.
Show answer
Run aws ec2 create-tags --resources i-0123456789abcdef0 --tags Key=Name,Value=web-1 Key=Env,Value=dev --dry-run. A successful check returns an error of type DryRunOperation saying the request would have succeeded. An UnauthorizedOperation error means your identity lacks the permission.