AWS CLI Cheat Sheet
Quick reference for the most common AWS CLI commands across core services. Assumes AWS CLI v2 is installed and configured.
Related: Terraform Cheat Sheet | Docker Cheat Sheet
Setup & Configuration
| Command | Description |
|---|---|
aws configure | Interactive setup (access key, secret, region, output) |
aws configure --profile staging | Configure a named profile |
aws configure list | Show current config values |
aws sts get-caller-identity | Verify who you are authenticated as |
aws configure set region us-west-2 | Set default region |
export AWS_PROFILE=staging | Switch active profile via env var |
export AWS_DEFAULT_REGION=eu-west-1 | Override region via env var |
export AWS_REGION=eu-west-1 | Same; takes precedence over AWS_DEFAULT_REGION and is what the SDKs read |
aws configure list-profiles | List profile names |
aws configure get region --profile staging | Read one setting |
aws configure export-credentials --profile dev --format env | Print temporary credentials as export lines (for tools that don't understand SSO) |
aws --version | Check you are on v2 (aws-cli/2.x) |
TIP
Always verify your identity with aws sts get-caller-identity before running destructive commands. You might be in the wrong account.
SSO / IAM Identity Center Profiles (recommended over access keys)
# One-time setup: creates an sso-session and a profile in ~/.aws/config
aws configure sso
# SSO session name: my-org
# SSO start URL: https://my-org.awsapps.com/start
# SSO region: us-east-1
# Registration scopes: sso:account:access (default)
# ...then pick the account and role in the browser
# Daily use: log in once per session (token lasts hours, shared by all profiles of the session)
aws sso login --sso-session my-org # or: aws sso login --profile dev
aws sts get-caller-identity --profile dev
aws sso logout
# No browser on this machine (SSH, containers)
aws sso login --profile dev --use-device-code --no-browser
# ~/.aws/config
[sso-session my-org]
sso_start_url = https://my-org.awsapps.com/start
sso_region = us-east-1
sso_registration_scopes = sso:account:access
[profile dev]
sso_session = my-org
sso_account_id = 111111111111
sso_role_name = DeveloperAccess
region = eu-west-1
output = json
[profile prod-admin]
sso_session = my-org
sso_account_id = 222222222222
sso_role_name = AdministratorAccess
region = eu-west-1
# Assume a role using another profile's credentials (cross-account)
[profile prod-deploy]
source_profile = dev
role_arn = arn:aws:iam::222222222222:role/Deployer
region = eu-west-1
# mfa_serial = arn:aws:iam::111111111111:mfa/alice # prompts for MFA code
The [sso-session] format (CLI 2.9+) refreshes tokens automatically. Older "legacy" profiles that put sso_start_url directly in the profile still work but can't refresh.
Other Ways to Authenticate
| Method | Command / Setting | Use when |
|---|---|---|
| Console credentials | aws login (CLI 2.32+; --remote over SSH), aws logout | You already sign in to the AWS console with IAM or federation, no Identity Center |
| Environment variables | AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN | CI, short-lived credentials |
| CI OIDC federation | GitHub Actions aws-actions/configure-aws-credentials with role-to-assume | CI without long-lived keys |
| Instance / task role | Nothing to configure on EC2, ECS, Lambda | Code running inside AWS |
| External process | credential_process = /path/to/tool in a profile | Custom credential brokers |
| Long-term access keys | aws configure | Last resort; rotate and scope tightly |
Credential lookup order: command-line options → environment variables → aws login/SSO/assume-role profile settings → ~/.aws/credentials → container credentials → EC2 instance metadata.
EC2 (Elastic Compute Cloud)
Instance Management
| Command | Description |
|---|---|
aws ec2 describe-instances | List all EC2 instances |
aws ec2 describe-instances --filters "Name=instance-state-name,Values=running" | List only running instances |
aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId,State.Name,PublicIpAddress]' --output table | Clean tabular output |
aws ec2 start-instances --instance-ids i-1234567890abcdef0 | Start an instance |
aws ec2 stop-instances --instance-ids i-1234567890abcdef0 | Stop an instance |
aws ec2 reboot-instances --instance-ids i-1234567890abcdef0 | Reboot an instance |
aws ec2 terminate-instances --instance-ids i-1234567890abcdef0 | Terminate (delete) an instance |
aws ec2 describe-instances --filters "Name=tag:Env,Values=prod" | Filter by tag |
aws ec2 wait instance-running --instance-ids i-1234567890abcdef0 | Block until running (wait exists for many resources) |
aws ec2 describe-images --owners amazon --filters "Name=name,Values=al2023-ami-*-x86_64" --query 'sort_by(Images,&CreationDate)[-1].ImageId' --output text | Latest Amazon Linux 2023 AMI |
aws ssm get-parameter --name /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 --query Parameter.Value --output text | Same via public SSM parameter |
aws ec2 run-instances --image-id ami-xxx --instance-type t4g.micro --key-name my-key --subnet-id subnet-xxx --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=web}]' | Launch an instance |
aws ec2 describe-regions --query 'Regions[].RegionName' --output text | List enabled regions |
Connect Without SSH Keys (SSM Session Manager)
# Needs the Session Manager plugin installed locally and the SSM agent + instance role on the instance
aws ssm start-session --target i-1234567890abcdef0
# Port forward to a private RDS through an instance
aws ssm start-session --target i-1234567890abcdef0 \
--document-name AWS-StartPortForwardingSessionToRemoteHost \
--parameters '{"host":["mydb.xxx.eu-west-1.rds.amazonaws.com"],"portNumber":["5432"],"localPortNumber":["5432"]}'
Security Groups
| Command | Description |
|---|---|
aws ec2 describe-security-groups | List all security groups |
aws ec2 authorize-security-group-ingress --group-id sg-xxx --protocol tcp --port 443 --cidr 0.0.0.0/0 | Allow HTTPS from anywhere |
aws ec2 revoke-security-group-ingress --group-id sg-xxx --protocol tcp --port 22 --cidr 0.0.0.0/0 | Remove SSH access |
Key Pairs
| Command | Description |
|---|---|
aws ec2 create-key-pair --key-name my-key --query 'KeyMaterial' --output text > my-key.pem | Create and save key pair |
aws ec2 describe-key-pairs | List key pairs |
aws ec2 delete-key-pair --key-name my-key | Delete key pair |
S3 (Simple Storage Service)
Bucket Operations
| Command | Description |
|---|---|
aws s3 ls | List all buckets |
aws s3 ls s3://my-bucket | List top-level objects in bucket |
aws s3 ls s3://my-bucket --recursive --human-readable | List all objects with human-readable sizes |
aws s3 mb s3://my-new-bucket | Create a bucket |
aws s3 rb s3://my-bucket | Remove an empty bucket |
aws s3 rb s3://my-bucket --force | Remove bucket and all contents |
File Operations
| Command | Description |
|---|---|
aws s3 cp file.txt s3://bucket/path/ | Upload file |
aws s3 cp s3://bucket/path/file.txt . | Download file |
aws s3 cp s3://bucket/a.txt s3://bucket/b.txt | Copy within S3 |
aws s3 mv file.txt s3://bucket/path/ | Move file to S3 |
aws s3 rm s3://bucket/path/file.txt | Delete file |
aws s3 sync ./local-dir s3://bucket/path/ | Sync local directory to S3 |
aws s3 sync s3://bucket/path/ ./local-dir | Sync S3 to local directory |
aws s3 sync . s3://bucket/ --exclude "*.log" | Sync excluding patterns |
aws s3 sync . s3://bucket/ --delete | Sync and remove deleted files |
aws s3 sync . s3://bucket/ --dryrun | Show what sync would do (note: --dryrun, no hyphen) |
aws s3 cp ./dir s3://bucket/dir --recursive | Upload a directory |
aws s3 cp s3://bucket/ . --recursive --exclude "*" --include "*.csv" | Download only matching files (filters apply in order) |
aws s3 cp file.txt s3://bucket/ --sse aws:kms --storage-class STANDARD_IA | Upload with encryption and storage class |
aws s3 cp - s3://bucket/dump.sql.gz | Upload from stdin (pg_dump ... | gzip | aws s3 cp - s3://...) |
aws s3 cp s3://bucket/file.txt - | Stream an object to stdout |
aws s3 ls s3://bucket/prefix/ --recursive --summarize --human-readable | Total object count and size under a prefix |
s3api (Low-Level)
| Command | Description |
|---|---|
aws s3api head-object --bucket b --key k | Object metadata (size, ETag, storage class) |
aws s3api list-objects-v2 --bucket b --prefix logs/ --query 'Contents[].Key' | List keys (auto-paginates) |
aws s3api put-bucket-versioning --bucket b --versioning-configuration Status=Enabled | Turn on versioning |
aws s3api list-object-versions --bucket b --prefix k | See versions and delete markers |
aws s3api get-bucket-policy --bucket b --query Policy --output text | jq . | Read the bucket policy |
aws s3api put-public-access-block --bucket b --public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true | Block all public access |
Presigned URLs
| Command | Description |
|---|---|
aws s3 presign s3://bucket/file.txt --expires-in 3600 | Generate presigned URL (1 hour) |
aws s3 presign only creates download (GET) URLs. The maximum is 7 days (604800 s), and a URL signed with temporary credentials (SSO, assumed role) stops working when those credentials expire, often much sooner. For presigned uploads use an SDK (PutObject presign or a presigned POST).
WARNING
aws s3 sync --delete will remove files in the destination that do not exist in the source. Double-check direction before running.
IAM (Identity and Access Management)
Users & Groups
| Command | Description |
|---|---|
aws iam list-users | List all IAM users |
aws iam create-user --user-name dev-user | Create a user |
aws iam delete-user --user-name dev-user | Delete a user |
aws iam list-groups | List all groups |
aws iam add-user-to-group --user-name dev-user --group-name developers | Add user to group |
aws iam create-access-key --user-name dev-user | Create access key for user |
aws iam list-access-keys --user-name dev-user | List user's access keys |
aws iam delete-access-key --user-name dev-user --access-key-id AKIAXXXXXXX | Delete access key |
Roles & Policies
| Command | Description |
|---|---|
aws iam list-roles | List all roles |
aws iam list-policies --scope Local | List customer-managed policies |
aws iam attach-role-policy --role-name my-role --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess | Attach policy to role |
aws iam list-attached-role-policies --role-name my-role | List policies attached to role |
aws iam get-policy --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess | Get policy details |
aws iam simulate-principal-policy --policy-source-arn arn:aws:iam::123456:user/dev --action-names s3:GetObject | Test permissions |
aws iam create-role --role-name my-role --assume-role-policy-document file://trust.json | Create a role with a trust policy |
aws iam put-role-policy --role-name my-role --policy-name inline --policy-document file://policy.json | Add an inline policy |
aws iam get-role --role-name my-role --query Role.AssumeRolePolicyDocument | Who can assume this role? |
aws sts decode-authorization-message --encoded-message <msg> | Decode an "encoded authorization failure" message (needs sts:DecodeAuthorizationMessage) |
Lambda
| Command | Description |
|---|---|
aws lambda list-functions | List all Lambda functions |
aws lambda get-function --function-name my-func | Get function details |
aws lambda invoke --function-name my-func --cli-binary-format raw-in-base64-out --payload '{"key":"val"}' output.json | Invoke function synchronously (v2 expects base64 payloads unless you pass --cli-binary-format raw-in-base64-out) |
aws lambda invoke --function-name my-func --invocation-type Event --cli-binary-format raw-in-base64-out --payload '{}' output.json | Invoke asynchronously |
aws lambda invoke --function-name my-func --payload fileb://event.json out.json | Payload from a file (fileb:// sends the bytes as-is) |
aws lambda invoke --function-name my-func --log-type Tail out.json --query LogResult --output text | base64 -d | Invoke and print the last 4 KB of logs |
aws lambda update-function-code --function-name my-func --zip-file fileb://function.zip | Deploy new code from zip |
aws lambda update-function-configuration --function-name my-func --memory-size 512 --timeout 30 | Update config |
aws lambda publish-version --function-name my-func | Publish a version |
aws lambda list-versions-by-function --function-name my-func | List versions |
aws lambda create-alias --function-name my-func --name prod --function-version 5 | Create alias pointing to version |
aws lambda get-function-configuration --function-name my-func | Get runtime config |
aws lambda update-function-code --function-name my-func --image-uri 123456789012.dkr.ecr.eu-west-1.amazonaws.com/my-func:v2 | Deploy a container image |
aws lambda wait function-updated-v2 --function-name my-func | Wait for an update to finish before the next one |
aws lambda update-function-configuration --function-name my-func --environment 'Variables={LOG_LEVEL=debug}' | Set env vars (replaces all existing ones) |
Back-to-back update-function-code and update-function-configuration calls fail with ResourceConflictException while the first update is in progress; put a wait function-updated-v2 between them.
Lambda Logs
# Get recent log streams
aws logs describe-log-streams \
--log-group-name /aws/lambda/my-func \
--order-by LastEventTime \
--descending \
--limit 5
# Tail live logs
aws logs tail /aws/lambda/my-func --follow
# Last hour, only errors, compact format
aws logs tail /aws/lambda/my-func --since 1h --filter-pattern ERROR --format short
RDS (Relational Database Service)
| Command | Description |
|---|---|
aws rds describe-db-instances | List all RDS instances |
aws rds describe-db-instances --query 'DBInstances[*].[DBInstanceIdentifier,DBInstanceStatus,Endpoint.Address]' --output table | Clean table output |
aws rds create-db-snapshot --db-instance-identifier mydb --db-snapshot-identifier mydb-snap | Create snapshot |
aws rds describe-db-snapshots --db-instance-identifier mydb | List snapshots |
aws rds restore-db-instance-from-db-snapshot --db-instance-identifier mydb-restored --db-snapshot-identifier mydb-snap | Restore from snapshot |
aws rds stop-db-instance --db-instance-identifier mydb | Stop instance (saves cost) |
aws rds start-db-instance --db-instance-identifier mydb | Start instance |
aws rds modify-db-instance --db-instance-identifier mydb --db-instance-class db.r5.large --apply-immediately | Change instance type |
DANGER
--apply-immediately causes downtime for most modifications. Use --no-apply-immediately to defer to the next maintenance window.
ECS (Elastic Container Service)
Cluster & Service Management
| Command | Description |
|---|---|
aws ecs list-clusters | List all ECS clusters |
aws ecs describe-clusters --clusters my-cluster | Get cluster details |
aws ecs list-services --cluster my-cluster | List services in a cluster |
aws ecs describe-services --cluster my-cluster --services my-svc | Get service details |
aws ecs update-service --cluster my-cluster --service my-svc --desired-count 3 | Scale service |
aws ecs update-service --cluster my-cluster --service my-svc --force-new-deployment | Force redeploy |
Tasks
| Command | Description |
|---|---|
aws ecs list-tasks --cluster my-cluster --service-name my-svc | List running tasks |
aws ecs describe-tasks --cluster my-cluster --tasks arn:aws:ecs:... | Get task details |
aws ecs stop-task --cluster my-cluster --task arn:aws:ecs:... | Stop a task |
aws ecs run-task --cluster my-cluster --task-definition my-td:3 | Run a one-off task |
aws ecs execute-command --cluster my-cluster --task arn --container app --interactive --command "/bin/sh" | Shell into running container (needs the Session Manager plugin, --enable-execute-command on the service/task, and SSM permissions on the task role) |
aws ecs update-service --cluster my-cluster --service my-svc --enable-execute-command --force-new-deployment | Turn on ECS Exec for a service |
aws ecs describe-tasks --cluster my-cluster --tasks <arn> --query 'tasks[].{status:lastStatus,reason:stoppedReason,containers:containers[].reason}' | Why did a task stop? |
aws ecs wait services-stable --cluster my-cluster --services my-svc | Wait for a deployment to finish |
ECR
# Log Docker in to ECR (token valid 12 hours)
aws ecr get-login-password --region eu-west-1 | \
docker login --username AWS --password-stdin 123456789012.dkr.ecr.eu-west-1.amazonaws.com
aws ecr create-repository --repository-name my-app --image-scanning-configuration scanOnPush=true
aws ecr describe-images --repository-name my-app --query 'sort_by(imageDetails,&imagePushedAt)[-5:].imageTags'
Task Definitions
| Command | Description |
|---|---|
aws ecs list-task-definitions | List all task definitions |
aws ecs describe-task-definition --task-definition my-td:3 | Get task definition |
aws ecs register-task-definition --cli-input-json file://task-def.json | Register new task definition |
aws ecs deregister-task-definition --task-definition my-td:1 | Deregister old revision |
CloudWatch
| Command | Description |
|---|---|
aws logs describe-log-groups | List log groups |
aws logs tail /ecs/my-service --follow | Tail logs in real time |
aws logs filter-log-events --log-group-name /ecs/my-svc --filter-pattern "ERROR" | Search for errors |
aws cloudwatch list-metrics --namespace AWS/EC2 | List available metrics |
aws cloudwatch get-metric-statistics --namespace AWS/EC2 --metric-name CPUUtilization --dimensions Name=InstanceId,Value=i-xxx --start-time 2024-01-01T00:00:00Z --end-time 2024-01-02T00:00:00Z --period 3600 --statistics Average | Get CPU stats |
aws cloudwatch describe-alarms --state-value ALARM | Alarms currently firing |
Logs Insights from the CLI
qid=$(aws logs start-query \
--log-group-name /aws/lambda/my-func \
--start-time $(date -d '-1 hour' +%s) --end-time $(date +%s) \
--query-string 'fields @timestamp, @message | filter @message like /ERROR/ | sort @timestamp desc | limit 20' \
--query queryId --output text)
sleep 5
aws logs get-query-results --query-id "$qid"
(date -d is GNU; on macOS use date -v-1H +%s.)
Secrets & Parameters
| Command | Description |
|---|---|
aws secretsmanager get-secret-value --secret-id prod/db --query SecretString --output text | Read a secret |
aws secretsmanager create-secret --name prod/db --secret-string file://secret.json | Create a secret |
aws ssm get-parameter --name /app/prod/db-url --with-decryption --query Parameter.Value --output text | Read a SecureString parameter |
aws ssm get-parameters-by-path --path /app/prod --recursive --with-decryption | All parameters under a path |
aws ssm put-parameter --name /app/prod/flag --value on --type String --overwrite | Create/update a parameter |
CloudFormation
| Command | Description |
|---|---|
aws cloudformation deploy --template-file t.yaml --stack-name app --capabilities CAPABILITY_NAMED_IAM --parameter-overrides Env=prod | Create or update a stack via a change set |
aws cloudformation describe-stack-events --stack-name app --max-items 20 | Why did it fail? |
aws cloudformation describe-stacks --stack-name app --query 'Stacks[0].Outputs' | Stack outputs |
aws cloudformation delete-stack --stack-name app | Delete a stack |
Useful Patterns
Find Expensive Resources
# Large S3 buckets: size per bucket from the daily CloudWatch storage metric
# (run in each bucket's region; StorageType differs per storage class)
for b in $(aws s3api list-buckets --query 'Buckets[].Name' --output text); do
size=$(aws cloudwatch get-metric-statistics --namespace AWS/S3 --metric-name BucketSizeBytes \
--dimensions Name=BucketName,Value="$b" Name=StorageType,Value=StandardStorage \
--start-time "$(date -u -d '-2 days' +%FT%TZ)" --end-time "$(date -u +%FT%TZ)" \
--period 86400 --statistics Average --query 'Datapoints[0].Average' --output text)
echo "$size $b"
done | sort -rn | head
# Unattached EBS volumes (paying for nothing)
aws ec2 describe-volumes --filters Name=status,Values=available \
--query 'Volumes[].[VolumeId,Size,CreateTime]' --output table
# Unassociated Elastic IPs (billed)
aws ec2 describe-addresses --query 'Addresses[?AssociationId==null].PublicIp'
# Cost by service, last month (Cost Explorer API costs $0.01 per request)
aws ce get-cost-and-usage --time-period Start=2026-10-01,End=2026-11-01 \
--granularity MONTHLY --metrics UnblendedCost \
--group-by Type=DIMENSION,Key=SERVICE \
--query 'ResultsByTime[0].Groups[].[Keys[0],Metrics.UnblendedCost.Amount]' --output text | sort -k2 -rn | head
# Running EC2 instances and their types
aws ec2 describe-instances \
--filters "Name=instance-state-name,Values=running" \
--query 'Reservations[*].Instances[*].[InstanceId,InstanceType,LaunchTime]' \
--output table
Multi-Account Operations
# Assume role in another account
CREDS=$(aws sts assume-role \
--role-arn arn:aws:iam::TARGET_ACCOUNT:role/CrossAccountRole \
--role-session-name my-session \
--query 'Credentials')
export AWS_ACCESS_KEY_ID=$(echo $CREDS | jq -r '.AccessKeyId')
export AWS_SECRET_ACCESS_KEY=$(echo $CREDS | jq -r '.SecretAccessKey')
export AWS_SESSION_TOKEN=$(echo $CREDS | jq -r '.SessionToken')
# Without jq
read -r AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN < <(aws sts assume-role \
--role-arn arn:aws:iam::TARGET_ACCOUNT:role/CrossAccountRole --role-session-name my-session \
--query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]' --output text)
export AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
# Simpler: a profile with role_arn + source_profile (see SSO section), then
aws s3 ls --profile prod-deploy
# Run the same command in every region
for r in $(aws ec2 describe-regions --query 'Regions[].RegionName' --output text); do
echo "== $r"; aws ec2 describe-instances --region "$r" --query 'Reservations[].Instances[].InstanceId' --output text
done
JMESPath --query Patterns
| Pattern | Meaning |
|---|---|
Reservations[].Instances[] | Flatten nested lists |
[?State.Name=='running'] | Filter |
[?contains(Tags[?Key=='Name'].Value | [0], 'web')] | Filter by tag value substring |
[].{id:InstanceId,type:InstanceType} | Reshape into objects |
sort_by(Images,&CreationDate)[-1] | Newest item |
length(Buckets) | Count |
Tags[?Key=='Name'].Value | [0] | Single tag value |
Use backticks for literals in JMESPath, e.g. [?Size > `100`], and quote the whole query in single quotes so the shell leaves it alone.
Pagination
The CLI auto-paginates (fetches every page) by default. --max-items 50 caps results and prints a NextToken; continue with --starting-token <token>. --page-size only changes how many items each API call fetches (useful to avoid timeouts). --no-paginate returns only the first page.
Output Formatting
# Table output
aws ec2 describe-instances --output table
# JSON with jq
aws ec2 describe-instances | jq '.Reservations[].Instances[] | {id: .InstanceId, state: .State.Name}'
# Text output (great for scripting)
aws ec2 describe-instances --query 'Reservations[*].Instances[*].InstanceId' --output text
# YAML output
aws ec2 describe-instances --output yaml
TIP
Use --query (JMESPath) for server-side filtering, and jq for client-side transformation. Combine both for complex queries.
Common Flags
| Flag | Description |
|---|---|
--profile name | Use a named profile |
--region us-east-1 | Override region |
--output json|table|text|yaml | Output format |
--query 'JMESPath' | Filter/transform output |
--no-cli-pager | Disable pager for scripting |
--dry-run | Test permissions without executing (EC2) |
--debug | Full debug output |
--cli-binary-format raw-in-base64-out | Pass blob parameters (Lambda payloads, Kinesis data) as raw text |
--cli-input-json file://req.json / --cli-input-yaml | Read all parameters from a file |
--generate-cli-skeleton | Print a JSON template of every parameter |
--endpoint-url http://localhost:4566 | Talk to LocalStack or another compatible endpoint |
--no-sign-request | Anonymous access (public buckets) |
--cli-auto-prompt | Interactive prompt with completion for any command |
file:// vs fileb:// | Read a parameter from a text file / as raw bytes |
Put cli_pager = (empty) and cli_binary_format = raw-in-base64-out under [default] in ~/.aws/config to make both behaviours permanent. AWS_PAGER="" disables the pager via env var.
Test Yourself
-
What command verifies which AWS account and IAM identity you are using?
aws sts get-caller-identity -
How do you sync a local directory to S3, deleting files in S3 that no longer exist locally?
aws s3 sync . s3://bucket/ --delete -
What command generates a presigned URL valid for 1 hour?
aws s3 presign s3://bucket/file.txt --expires-in 3600 -
How do you invoke a Lambda function asynchronously?
aws lambda invoke --function-name my-func --invocation-type Event --payload '{}' output.json -
What command tails CloudWatch logs in real time?
aws logs tail /aws/lambda/my-func --follow -
How do you list only running EC2 instances?
aws ec2 describe-instances --filters "Name=instance-state-name,Values=running" -
What flag switches the active AWS profile via environment variable?
export AWS_PROFILE=staging -
How do you force a new deployment of an ECS service?
aws ecs update-service --cluster my-cluster --service my-svc --force-new-deployment -
What flag disables the pager for scripting?
--no-cli-pager -
How do you assume a role in another AWS account?
aws sts assume-role --role-arn arn:aws:iam::TARGET:role/Role --role-session-name session
Common Gotchas
aws s3 sync --deletecan delete production data. It removes files in the destination that are not in the source. Always double-check the sync direction (source vs destination).- Running destructive commands in the wrong account. Always verify with
aws sts get-caller-identitybefore runningterminate-instances,delete-bucket, or similar commands. --apply-immediatelyon RDS causes downtime. Most RDS modifications trigger a restart. Use--no-apply-immediatelyto defer to the next maintenance window.- Forgetting
--regionwith global services. Some resources (like S3 buckets) are global but created in a specific region. IAM is truly global but CloudWatch metrics are regional. - CLI v2 treats blobs as base64.
aws lambda invoke --payload '{"a":1}'fails with "Invalid base64" unless you add--cli-binary-format raw-in-base64-out(or set it in config). aws s3 rb --forcedoesn't empty versioned buckets. Old versions and delete markers remain, so the delete fails. Delete versions first (or set a lifecycle rule), or use the console's "Empty" button.aws s3 synccompares size and timestamp, not content. A same-size file with an older timestamp is skipped. Use--exact-timestamps(download) orcp --recursivewhen in doubt.- SSO token expired. Errors like "Token has expired and refresh failed" or "Error loading SSO Token" mean run
aws sso loginagain, not reconfigure. --output textflattens nested lists. Multiple values per row come out tab-separated and can wrap unexpectedly; for scripts prefer--querythat returns a flat list, or JSON plusjq.- The pager hangs scripts and CI. v2 pipes output through
lessby default. Use--no-cli-pagerorAWS_PAGER="".
One-Liner Summary
The AWS CLI is your command-line interface to every AWS service -- master sts get-caller-identity, s3 sync, --query JMESPath filters, and named profiles to operate safely across accounts.
Last updated: 2026-11-09