AWS CLI Cheatsheet
The AWS Command Line Interface (AWS CLI) is a unified tool to manage your AWS services from the command line.
Core Concepts
- Command Structure:
aws [service] [operation] [parameters]
- Example:
aws ec2 describe-instances --instance-ids i-1234567890abcdef0
- Example:
- Configuration: Stored primarily in
~/.aws/config
(settings like region, output format) and~/.aws/credentials
(access keys). Useaws configure
to set up. - Profiles: Named sets of configurations and credentials. Use
--profile [PROFILE_NAME]
to switch. Thedefault
profile is used if none is specified. - Region: Specify the AWS region using
--region [REGION_CODE]
(e.g.,us-east-1
) or set a default in the config file. - Output Formats: Control output with
--output [FORMAT]
(json
,text
,table
,yaml
,yaml-stream
). - Client-Side Filtering: Use
--query "[JMESPATH_EXPRESSION]"
to filter JSON output after it's received from AWS. - Server-Side Filtering: Many
list
ordescribe
operations support--filters Name=...,Values=...
to filter results before they are sent from AWS (more efficient). - Pagination: Control how many items are returned per API call (
--page-size
) and the total items (--max-items
). Use--no-cli-pager
to disable the default pager (likeless
).
Installation & Configuration
- Install/Update: Follow official instructions: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html
# Example using pip (ensure Python/pip is installed) pip install awscli --upgrade --user
- Initial Configuration (Interactive): Sets up the
default
profile. Prompts for Access Key ID, Secret Access Key, Default Region, and Default Output Format.aws configure
- Configure a Named Profile:
aws configure --profile my-other-profile
- List Configured Profiles:
aws configure list-profiles
- Show Current Configuration:
aws configure list
- Set a Specific Config Value:
aws configure set region us-west-2 --profile my-other-profile aws configure set default.region us-west-2 # Set default region for default profile
Authentication & Credentials
- Order of Precedence:
- Command line options (
--region
, access keys via parameters if applicable) - Environment variables (
AWS_ACCESS_KEY_ID
,AWS_SECRET_ACCESS_KEY
,AWS_SESSION_TOKEN
,AWS_DEFAULT_REGION
,AWS_PROFILE
) - CLI credential file (
~/.aws/credentials
) - CLI configuration file (
~/.aws/config
) - Container credentials (for ECS tasks or EKS pods with IAM roles)
- Instance profile credentials (for EC2 instances with IAM roles)
- Command line options (
- Assume Role (STS): Get temporary credentials for a role.
aws sts assume-role --role-arn arn:aws:iam::123456789012:role/MyRole --role-session-name MySession # Often combined with setting environment variables or configuring a profile
- Get Caller Identity: Verify the identity being used by the CLI.
aws sts get-caller-identity
Common Global Options
--profile [PROFILE_NAME]
: Use a specific named profile.--region [REGION_CODE]
: Override the default region for this command.--output [json|text|table|yaml|yaml-stream]
: Specify the output format.--query "[JMESPATH]"
: Filter JSON output client-side.--no-cli-pager
: Disable the output pager.--debug
: Show detailed debug information, including HTTP requests/responses.--endpoint-url [URL]
: Use a custom service endpoint (e.g., for LocalStack, VPC endpoints).
Output Control Examples
- Get JSON (Default):
aws ec2 describe-instances
- Get Table Output:
aws ec2 describe-instances --query "Reservations[*].Instances[*].[InstanceId, State.Name, Placement.AvailabilityZone]" --output table
- Get Text Output (Tab-separated):
aws ec2 describe-instances --query "Reservations[*].Instances[*].[InstanceId, State.Name, Placement.AvailabilityZone]" --output text
- Query Specific Fields:
aws iam list-users --query 'Users[*].UserName' --output text
- Filter with JMESPath: Get running instance IDs in us-east-1a.
aws ec2 describe-instances --query "Reservations[*].Instances[?Placement.AvailabilityZone=='us-east-1a' && State.Name=='running'].InstanceId" --output text
Common Service Commands (Examples)
(Replace [PLACEHOLDERS]
with your values)
EC2 (Elastic Compute Cloud)
- Describe instances (use
--filters
for server-side filtering):aws ec2 describe-instances \ --filters Name=instance-state-name,Values=running Name=tag:Environment,Values=Production \ --query "Reservations[*].Instances[*].[InstanceId, PrivateIpAddress, Tags[?Key=='Name'].Value | [0]]" \ --output table
- Run (launch) an instance:
aws ec2 run-instances \ --image-id ami-0abcdef1234567890 \ --instance-type t2.micro \ --key-name MyKeyPair \ --security-group-ids sg-12345678 \ --subnet-id subnet-abcdef12 \ --count 1 \ --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=MyWebServer}]'
- Stop instances:
aws ec2 stop-instances --instance-ids i-123... i-456...
- Start instances:
aws ec2 start-instances --instance-ids i-123...
- Terminate instances:
aws ec2 terminate-instances --instance-ids i-123...
- Describe VPCs:
aws ec2 describe-vpcs
- Describe Subnets:
aws ec2 describe-subnets
- Describe Security Groups:
aws ec2 describe-security-groups
S3 (Simple Storage Service)
-
High-Level
s3
Commands (Recommended for files/objects):- List buckets:
aws s3 ls
- List objects in a bucket/prefix:
aws s3 ls s3://[BUCKET_NAME]/[PREFIX]/
- Copy file/object:
- Local to S3:
aws s3 cp my-file.txt s3://[BUCKET_NAME]/
- S3 to Local:
aws s3 cp s3://[BUCKET_NAME]/my-object.txt .
- S3 to S3:
aws s3 cp s3://[BUCKET1]/obj1 s3://[BUCKET2]/obj2
- Local to S3:
- Sync directory:
- Local to S3:
aws s3 sync ./local-dir/ s3://[BUCKET_NAME]/remote-dir/
- S3 to Local:
aws s3 sync s3://[BUCKET_NAME]/remote-dir/ ./local-dir/
- Local to S3:
- Move object:
aws s3 mv s3://[BUCKET_NAME]/old.txt s3://[BUCKET_NAME]/new.txt
- Remove object:
aws s3 rm s3://[BUCKET_NAME]/my-object.txt
- Remove objects recursively:
aws s3 rm s3://[BUCKET_NAME]/my-folder/ --recursive
- Create bucket:
aws s3 mb s3://[UNIQUE_BUCKET_NAME] --region [REGION_CODE]
(useus-east-1
if region omitted) - Remove bucket (must be empty):
aws s3 rb s3://[BUCKET_NAME]
- Remove bucket and contents:
aws s3 rb s3://[BUCKET_NAME] --force
- List buckets:
-
Low-Level
s3api
Commands (Direct API mapping, for bucket policies, etc.):- List objects (API):
aws s3api list-objects-v2 --bucket [BUCKET_NAME]
- Get object details:
aws s3api head-object --bucket [BUCKET_NAME] --key path/to/object.txt
- Delete object (API):
aws s3api delete-object --bucket [BUCKET_NAME] --key path/to/object.txt
- Get bucket policy:
aws s3api get-bucket-policy --bucket [BUCKET_NAME]
- Put bucket policy:
aws s3api put-bucket-policy --bucket [BUCKET_NAME] --policy file://policy.json
- List objects (API):
IAM (Identity and Access Management)
- List users:
aws iam list-users
- Get user details:
aws iam get-user --user-name [USERNAME]
- Create user:
aws iam create-user --user-name [USERNAME]
- Delete user:
aws iam delete-user --user-name [USERNAME]
- List roles:
aws iam list-roles
- Get role:
aws iam get-role --role-name [ROLENAME]
- List attached user policies:
aws iam list-attached-user-policies --user-name [USERNAME]
- Attach policy to user:
aws iam attach-user-policy --user-name [USERNAME] --policy-arn [POLICY_ARN]
- Detach policy from user:
aws iam detach-user-policy --user-name [USERNAME] --policy-arn [POLICY_ARN]
Lambda
- List functions:
aws lambda list-functions
- Get function configuration:
aws lambda get-function --function-name [FUNCTION_NAME]
- Invoke function:
aws lambda invoke --function-name [FUNCTION_NAME] --payload '{"key": "value"}' output.json cat output.json # View response payload
- Update function code (from zip):
aws lambda update-function-code --function-name [FUNCTION_NAME] --zip-file fileb://function.zip
- Delete function:
aws lambda delete-function --function-name [FUNCTION_NAME]
CloudWatch Logs
- List log groups:
aws logs describe-log-groups
- List log streams in a group:
aws logs describe-log-streams --log-group-name [LOG_GROUP_NAME]
- Get log events:
aws logs get-log-events --log-group-name [LOG_GROUP_NAME] --log-stream-name [LOG_STREAM_NAME] --limit 5 # Get logs within a time range (timestamps in milliseconds since epoch) aws logs filter-log-events --log-group-name [LOG_GROUP_NAME] --start-time [START_TIMESTAMP_MS] --end-time [END_TIMESTAMP_MS]
CloudFormation
- List stacks:
aws cloudformation list-stacks --stack-status-filter CREATE_COMPLETE UPDATE_COMPLETE
- Describe stack:
aws cloudformation describe-stacks --stack-name [STACK_NAME]
- Create stack:
aws cloudformation create-stack --stack-name [STACK_NAME] --template-body file://template.yaml --parameters ParameterKey=Key1,ParameterValue=Val1
- Update stack:
aws cloudformation update-stack --stack-name [STACK_NAME] --template-body file://template.yaml
- Delete stack:
aws cloudformation delete-stack --stack-name [STACK_NAME]
- Validate template:
aws cloudformation validate-template --template-body file://template.yaml
DynamoDB
- List tables:
aws dynamodb list-tables
- Describe table:
aws dynamodb describe-table --table-name [TABLE_NAME]
- Put item (note the JSON format for attributes):
aws dynamodb put-item --table-name [TABLE_NAME] --item '{"Id": {"S": "item1"}, "AttributeName": {"N": "123"}}'
- Get item:
aws dynamodb get-item --table-name [TABLE_NAME] --key '{"Id": {"S": "item1"}}'
- Query table (requires index key):
aws dynamodb query --table-name [TABLE_NAME] --key-condition-expression "Id = :v1" --expression-attribute-values '{":v1": {"S": "item1"}}'
- Scan table (reads entire table - use with caution):
aws dynamodb scan --table-name [TABLE_NAME]
Scripting Tips
- Use
--output text
or--output json
combined with tools likejq
for parsing in scripts. - Use
--query
to extract specific values needed. - Check the exit code (
$?
in bash) after each command to detect errors (0 means success). - Use
--no-cli-pager
in non-interactive scripts. - Leverage environment variables for credentials and region in automated environments (CI/CD, EC2 instance roles).
Getting Help
- General help:
aws help
- Help for a specific service (e.g., ec2):
aws ec2 help
- Help for a specific operation (e.g., ec2 describe-instances):
aws ec2 describe-instances help
Always refer to the official AWS CLI documentation for the most accurate and complete information. https://docs.aws.amazon.com/cli/