AWS CLI
Production Surface

aws sts get-caller-identity

~30 services distilled to what engineers with production scars actually reach for. Honest about what doesn't belong here.

28 entries
7 phases
aws-cli v2, multi-account
What's not here, and why. cloudformation deploy is Terraform's job. cloudfront has no realistic CLI workflow under pressure. cloudtrail lookup-events is too slow to be useful interactively. dynamodb and elasticache are better accessed via SDK. codepipeline, codecommit, xray: console territory. If a service isn't on this page, that's a deliberate decision, not an oversight.
cross-cutting: know these before anything else
--query (JMESPath)
aws ec2 describe-instances --query 'Reservations[].Instances[].{ID:InstanceId,State:State.Name,IP:PrivateIpAddress}' --output table aws s3api list-objects-v2 --bucket mybucket --query 'Contents[?Size>`1048576`].[Key,Size]' --output text # [?field==`value`] filter, [*] flatten, {alias:path} projection
--output
aws ec2 describe-instances --output table aws ec2 describe-instances --output json | jq '.Reservations[].Instances[].InstanceId' aws ec2 describe-instances --output text --query 'Reservations[].Instances[].InstanceId' # text: tab-separated, no quotes; safe for xargs and shell pipelines
--profile / --region / env vars
aws s3 ls --profile prod --region eu-west-1 AWS_PROFILE=prod AWS_DEFAULT_REGION=eu-west-1 aws s3 ls aws configure list-profiles aws configure list --profile prod # credential chain: env vars → ~/.aws/credentials → instance profile → container role
pagination
aws s3api list-objects-v2 --bucket mybucket --page-size 100 --max-items 500 aws ec2 describe-instances --no-paginate aws ec2 describe-instances | jq '[.Reservations[].Instances[]] | length' # most list commands paginate silently. Always verify you got all results
Phase 28 shown
Service / CommandPhaseKey commandsUse case
sts auth
aws sts get-caller-identity aws sts assume-role --role-arn arn:aws:iam::123456789012:role/MyRole --role-session-name mysession eval $(aws sts assume-role --role-arn arn:aws:iam::123456789012:role/MyRole --role-session-name s --query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]' --output text | awk '{print "export AWS_ACCESS_KEY_ID="$1"\nexport AWS_SECRET_ACCESS_KEY="$2"\nexport AWS_SESSION_TOKEN="$3}') aws sts get-session-token --duration-seconds 43200 --serial-number arn:aws:iam::123456789012:mfa/myuser --token-code 123456
get-caller-identity is the first command to run when debugging "who am I and what account is this." The eval $(assume-role ...) pattern exports temp credentials into the current shell: fragile but useful in a pinch. Use aws-vault or granted instead for routine cross-account work.
aws-vault auth
aws-vault add myprofile aws-vault exec prod -- aws s3 ls aws-vault exec prod -- terraform plan aws-vault list aws-vault rotate myprofile # ~/.aws/config role chaining with aws-vault: # [profile prod] source_profile=base role_arn=arn:aws:iam::PROD:role/Admin mfa_serial=arn:aws:iam::BASE:mfa/me
Stores IAM credentials in the OS keychain. Never in plaintext on disk. exec injects temporary credentials into a subprocess without polluting the shell environment. MFA and role chaining are handled transparently via ~/.aws/config. Non-negotiable for multi-account work on a shared machine.
iam (inspection) auth
aws iam get-user aws iam list-attached-role-policies --role-name MyRole aws iam get-role --role-name MyRole --query 'Role.AssumeRolePolicyDocument' aws iam simulate-principal-policy --policy-source-arn arn:aws:iam::123:role/MyRole --action-names s3:PutObject --resource-arns arn:aws:s3:::mybucket/* aws iam generate-credential-report && aws iam get-credential-report --query 'Content' --output text | base64 -d
simulate-principal-policy is underused: answers "will this role be allowed to do X" without actually doing X. Credential report reveals last-used dates and access key age for all users. Run before a compliance audit. Keep IAM mutations in Terraform; use the CLI for inspection only.
sso auth
aws configure sso aws sso login --profile prod aws sso logout aws configure list-profiles | xargs -I{} aws sso login --profile {} # ~/.aws/config SSO profile: # [profile prod] # sso_start_url = https://myorg.awsapps.com/start # sso_account_id = 123456789012 # sso_role_name = AdministratorAccess # sso_region = eu-west-1
AWS IAM Identity Center (SSO) is the correct authentication path for organisations: no long-lived keys, MFA enforced at IdP, session duration controlled centrally. aws configure sso is a one-time setup per profile; after that aws sso login refreshes the session token. Prefer over IAM users for human access.
ec2 (inspection) compute
aws ec2 describe-instances --filters "Name=tag:Environment,Values=prod" "Name=instance-state-name,Values=running" --query 'Reservations[].Instances[].{ID:InstanceId,IP:PrivateIpAddress,Type:InstanceType,Name:Tags[?Key==`Name`].Value|[0]}' --output table aws ec2 describe-instances --instance-ids i-1234567890abcdef0 --query 'Reservations[0].Instances[0]' aws ec2 describe-instance-status --instance-ids i-1234567890abcdef0 aws ec2 stop-instances --instance-ids i-1234567890abcdef0 --dry-run aws ec2 describe-spot-price-history --instance-types m5.xlarge --product-descriptions "Linux/UNIX" --start-time $(date -u +%Y-%m-%dT%H:%M:%S) --query 'SpotPriceHistory[].{AZ:AvailabilityZone,Price:SpotPrice}' --output table
Tag-based filtering + JMESPath projection gives a clean inventory view without opening the console. --dry-run verifies permissions before a destructive operation. Spot price history is genuinely useful from the CLI: faster than the console graph for comparing AZs before a batch job submission.
ec2 (security groups) compute
aws ec2 describe-security-groups --query 'SecurityGroups[?IpPermissions[?IpRanges[?CidrIp==`0.0.0.0/0`]]].{ID:GroupId,Name:GroupName,Port:IpPermissions[].FromPort}' --output table aws ec2 describe-security-group-rules --filters "Name=group-id,Values=sg-12345" --query 'SecurityGroupRules[].{Dir:IsEgress,Port:FromPort,CIDR:CidrIpv4}' --output table aws ec2 authorize-security-group-ingress --group-id sg-12345 --protocol tcp --port 443 --cidr 10.0.0.0/8 aws ec2 revoke-security-group-ingress --group-id sg-12345 --protocol tcp --port 22 --cidr 0.0.0.0/0
The first query surfaces all security groups with a public ingress rule. Run it as a periodic audit, not just during incidents. describe-security-group-rules (not the older describe-security-groups) gives cleaner per-rule output. SG mutations belong in Terraform; use the CLI for emergency access changes only.
ecs compute
aws ecs list-clusters --query 'clusterArns[]' --output text aws ecs describe-services --cluster mycluster --services myservice --query 'services[0].{Status:status,Running:runningCount,Desired:desiredCount,Pending:pendingCount}' aws ecs list-tasks --cluster mycluster --service-name myservice --query 'taskArns' --output text | xargs aws ecs describe-tasks --cluster mycluster --tasks --query 'tasks[].{ID:taskArn,Status:lastStatus,Health:healthStatus}' aws ecs execute-command --cluster mycluster --task <task-id> --container mycontainer --command "/bin/sh" --interactive aws ecs update-service --cluster mycluster --service myservice --force-new-deployment
execute-command is ECS Exec: a shell into a running container without SSH or bastion. Requires the SSM agent in the task and enableExecuteCommand: true on the service. force-new-deployment triggers a rolling restart without changing the task definition: the correct way to pick up a new image on the same tag.
lambda compute
aws lambda invoke --function-name myfunction --payload '{"key":"value"}' --cli-binary-format raw-in-base64-out /tmp/response.json && cat /tmp/response.json aws lambda invoke --function-name myfunction --invocation-type Event --payload '{}' --cli-binary-format raw-in-base64-out /dev/null aws lambda get-function-configuration --function-name myfunction --query '{Memory:MemorySize,Timeout:Timeout,Runtime:Runtime,Handler:Handler}' aws lambda list-functions --query 'Functions[].{Name:FunctionName,Runtime:Runtime,Modified:LastModified}' --output table aws logs tail /aws/lambda/myfunction --follow
--cli-binary-format raw-in-base64-out is required in aws-cli v2 for JSON payloads: a silent breaking change from v1. --invocation-type Event fires async and returns immediately. Tail logs via aws logs, not the Lambda CLI. It has the filter syntax.
autoscaling compute
aws autoscaling describe-auto-scaling-groups --query 'AutoScalingGroups[].{Name:AutoScalingGroupName,Min:MinSize,Max:MaxSize,Desired:DesiredCapacity,Instances:Instances|length(@)}' --output table aws autoscaling describe-scaling-activities --auto-scaling-group-name my-asg --max-items 10 --query 'Activities[].{Time:StartTime,Status:StatusCode,Cause:Cause}' aws autoscaling set-desired-capacity --auto-scaling-group-name my-asg --desired-capacity 5 aws autoscaling terminate-instance-in-auto-scaling-group --instance-id i-1234567890abcdef0 --should-decrement-desired-capacity
describe-scaling-activities is the first place to look when an ASG isn't scaling as expected. It logs every scaling decision with a human-readable cause. terminate-instance with --should-decrement-desired-capacity removes a bad instance without triggering a replacement.
s3 (daily ops) storage
aws s3 ls s3://mybucket/prefix/ --recursive --human-readable --summarize aws s3 cp s3://mybucket/file.tar.gz ./file.tar.gz aws s3 sync ./local/ s3://mybucket/prefix/ --exclude "*.tmp" --delete aws s3 presign s3://mybucket/private-file.zip --expires-in 3600 aws s3 rm s3://mybucket/prefix/ --recursive --dryrun aws s3 mb s3://mybucket --region eu-west-1
sync --delete mirrors a local directory to S3, deleting remote objects with no local counterpart. Always run with --dryrun first. presign generates a time-limited authenticated URL without changing bucket policy: the correct way to share private objects temporarily.
s3api (advanced) storage
aws s3api get-bucket-policy --bucket mybucket | jq '.Policy | fromjson' aws s3api get-bucket-encryption --bucket mybucket aws s3api get-public-access-block --bucket mybucket aws s3api list-object-versions --bucket mybucket --prefix mykey --query '{Versions:Versions[].{Key:Key,ID:VersionId,Date:LastModified}}' aws s3api list-multipart-uploads --bucket mybucket aws s3api abort-multipart-upload --bucket mybucket --key mykey --upload-id <id>
get-public-access-block verifies the bucket-level block: a bucket policy allowing public access is silently blocked if this is set. Stale multipart uploads accumulate storage charges invisibly: list-multipart-uploads followed by abort clears them. Object versions are only visible via s3api, not s3.
ebs snapshots storage
aws ec2 describe-snapshots --owner-ids self --query 'Snapshots[].{ID:SnapshotId,Size:VolumeSize,State:State,Date:StartTime,Desc:Description}' --output table aws ec2 create-snapshot --volume-id vol-1234567890abcdef0 --description "pre-migration $(date +%Y%m%d)" aws ec2 describe-snapshots --owner-ids self --query 'Snapshots[?StartTime<=`2024-01-01`].SnapshotId' --output text | xargs -I{} aws ec2 delete-snapshot --snapshot-id {} aws ec2 copy-snapshot --source-region us-east-1 --source-snapshot-id snap-1234 --region eu-west-1 --description "cross-region copy"
Always create a snapshot before a risky operation and tag it with a date and reason. The delete pipeline pipes --output text snapshot IDs into xargs: verify the query returns the right set before removing --dry-run. Cross-region copy is the manual DR path when DLM isn't configured.
elbv2 networking
aws elbv2 describe-load-balancers --query 'LoadBalancers[].{Name:LoadBalancerName,DNS:DNSName,State:State.Code}' --output table aws elbv2 describe-target-health --target-group-arn arn:aws:elasticloadbalancing:... --query 'TargetHealthDescriptions[].{ID:Target.Id,Port:Target.Port,State:TargetHealth.State,Reason:TargetHealth.Reason}' aws elbv2 describe-rules --listener-arn <arn> --query 'Rules[].{Priority:Priority,Conditions:Conditions,Actions:Actions}' aws elbv2 describe-target-groups --load-balancer-arn <arn> --query 'TargetGroups[].{Name:TargetGroupName,Protocol:Protocol,Port:Port,HealthyThreshold:HealthyThresholdCount}'
describe-target-health with the Reason field is the first place to look when traffic isn't reaching instances: the reason string is specific enough to act on (health check failure, registration in progress, etc). Listener rules are opaque in the console; the CLI output is easier to audit for rule ordering bugs.
route53 networking
aws route53 list-hosted-zones --query 'HostedZones[].{Name:Name,ID:Id,Private:Config.PrivateZone}' --output table aws route53 list-resource-record-sets --hosted-zone-id Z1234 --query 'ResourceRecordSets[?Name==`api.example.com.`]' aws route53 change-resource-record-sets --hosted-zone-id Z1234 --change-batch file://record-change.json aws route53 test-dns-answer --hosted-zone-id Z1234 --record-name api.example.com --record-type A aws route53 get-health-check-status --health-check-id <id> --query 'HealthCheckObservations[].{Region:Region,Status:StatusReport.Status}'
test-dns-answer queries Route53 directly: bypasses resolver cache and propagation delay, answers "what does Route53 think the record is right now." Useful immediately after a change. Record mutations via change-batch JSON file are version-controllable: better than console edits for audit trails.
vpc / flow logs networking
aws ec2 describe-vpcs --query 'Vpcs[].{ID:VpcId,CIDR:CidrBlock,Default:IsDefault,Name:Tags[?Key==`Name`].Value|[0]}' --output table aws ec2 describe-subnets --filters "Name=vpc-id,Values=vpc-12345" --query 'Subnets[].{ID:SubnetId,AZ:AvailabilityZone,CIDR:CidrBlock,Public:MapPublicIpOnLaunch}' --output table aws ec2 describe-flow-logs --filter "Name=resource-id,Values=vpc-12345" aws logs filter-log-events --log-group-name /aws/vpc/flowlogs --filter-pattern "[version, account, eni, source, destination, srcport, destport, protocol, packets, bytes, windowstart, windowend, action=REJECT, flowlogstatus]" --start-time $(($(date +%s) - 3600))000 --query 'events[].message'
The flow log filter pattern surfaces all REJECT entries from the last hour: the fastest way to diagnose unexpected traffic drops from security groups or NACLs. describe-subnets with MapPublicIpOnLaunch identifies subnets that auto-assign public IPs: a common misconfiguration in multi-tier VPCs.
secretsmanager secrets
aws secretsmanager get-secret-value --secret-id myapp/prod/db --query 'SecretString' --output text | jq . aws secretsmanager get-secret-value --secret-id myapp/prod/db --query 'SecretString' --output text | jq -r '.password' aws secretsmanager list-secrets --query 'SecretList[].{Name:Name,LastChanged:LastChangedDate,LastAccessed:LastAccessedDate}' --output table aws secretsmanager rotate-secret --secret-id myapp/prod/db aws secretsmanager describe-secret --secret-id myapp/prod/db --query '{Rotation:RotationEnabled,Lambda:RotationLambdaARN,NextDate:NextRotationDate}'
Never print raw secret values to a terminal in a shared session. Pipe through jq -r '.password' to extract only what's needed. LastAccessedDate in the list view reveals unused secrets: candidates for deletion. describe-secret confirms rotation is configured before assuming it's running.
ssm parameter store secrets
aws ssm get-parameter --name /myapp/prod/db_url --with-decryption --query 'Parameter.Value' --output text aws ssm get-parameters-by-path --path /myapp/prod/ --recursive --with-decryption --query 'Parameters[].{Name:Name,Value:Value}' --output table aws ssm put-parameter --name /myapp/prod/api_key --value "mysecret" --type SecureString --overwrite aws ssm get-parameters-by-path --path /myapp/prod/ --recursive --query 'Parameters[].Name' --output text | tr '\t' '\n'
Hierarchical paths (/app/env/key) allow fetching all config for a service in one call with get-parameters-by-path --recursive. Always use SecureString for anything sensitive: String stores plaintext in the SSM API response and CloudTrail logs. Cheaper than Secrets Manager for non-rotating config.
ssm session manager secrets
aws ssm start-session --target i-1234567890abcdef0 aws ssm start-session --target i-1234567890abcdef0 --document-name AWS-StartPortForwardingSession --parameters '{"portNumber":["5432"],"localPortNumber":["15432"]}' aws ssm start-session --target i-1234567890abcdef0 --document-name AWS-StartPortForwardingSessionToRemoteHost --parameters '{"host":["rds.internal"],"portNumber":["5432"],"localPortNumber":["15432"]}' aws ssm send-command --instance-ids i-1234567890abcdef0 --document-name AWS-RunShellScript --parameters 'commands=["df -h"]' --query 'Command.CommandId'
SSH replacement: no open port 22, no key management, full audit trail in CloudTrail. Port forwarding to RDS or ElastiCache without a bastion is the pattern that replaces jump hosts entirely. send-command runs shell commands across a fleet without establishing interactive sessions: pairs with list-command-invocations for results.
cloudwatch logs observability
aws logs tail /aws/lambda/myfunction --follow aws logs tail /aws/ecs/myservice --since 1h --follow aws logs filter-log-events --log-group-name /aws/lambda/myfunction --filter-pattern "ERROR" --start-time $(($(date +%s) - 3600))000 --query 'events[].message' --output text aws logs start-query --log-group-name /aws/ecs/myservice --start-time $(($(date +%s) - 3600)) --end-time $(date +%s) --query-string 'fields @timestamp, @message | filter @message like /ERROR/ | sort @timestamp desc | limit 50' aws logs get-query-results --query-id <id> --query 'results[][?field==`@message`].value' --output text
aws logs tail --follow is the most-used command in this page during an incident: works for Lambda, ECS, and any CWL group. Timestamps for filter-log-events are millisecond epoch: the $(date +%s)000 pattern avoids tz mistakes. Insights queries via CLI are async: start-query returns an ID, poll with get-query-results.
cloudwatch metrics & alarms observability
aws cloudwatch describe-alarms --state-value ALARM --query 'MetricAlarms[].{Name:AlarmName,Reason:StateReason,Metric:MetricName}' --output table aws cloudwatch get-metric-statistics --namespace AWS/EC2 --metric-name CPUUtilization --dimensions Name=InstanceId,Value=i-1234567890abcdef0 --start-time $(date -u -v-1H +%Y-%m-%dT%H:%M:%S) --end-time $(date -u +%Y-%m-%dT%H:%M:%S) --period 300 --statistics Average --query 'Datapoints[].{Time:Timestamp,CPU:Average}' --output table aws cloudwatch set-alarm-state --alarm-name MyAlarm --state-value ALARM --state-reason "manual test" aws cloudwatch list-metrics --namespace AWS/RDS --query 'Metrics[].MetricName' --output text | tr '\t' '\n' | sort -u
describe-alarms --state-value ALARM is the first command during a pager event: shows what's firing and why without opening the console. set-alarm-state ALARM manually triggers an alarm to test SNS routing and runbook links without waiting for a real threshold breach.
sqs data / platform
aws sqs get-queue-attributes --queue-url https://sqs.eu-west-1.amazonaws.com/123/myqueue --attribute-names All --query 'Attributes.{Depth:ApproximateNumberOfMessages,InFlight:ApproximateNumberOfMessagesNotVisible,DLQ:RedrivePolicy}' aws sqs receive-message --queue-url <url> --max-number-of-messages 1 --query 'Messages[0].Body' --output text | jq . aws sqs purge-queue --queue-url <url> aws sqs start-message-move-task --source-arn arn:aws:sqs:eu-west-1:123:myqueue-dlq --destination-arn arn:aws:sqs:eu-west-1:123:myqueue # ApproximateNumberOfMessages is the backlog; InFlight is being processed
get-queue-attributes depth + in-flight split is the key metric for diagnosing processing lag vs consumer failures. start-message-move-task (SQS DLQ redrive) is the correct way to replay dead-letter messages: no manual receive-delete-send loop. purge-queue is irreversible; confirm you mean it.
sns data / platform
aws sns list-topics --query 'Topics[].TopicArn' --output text | tr '\t' '\n' aws sns publish --topic-arn arn:aws:sns:eu-west-1:123:mytopic --message '{"type":"test","payload":"hello"}' --message-structure raw aws sns list-subscriptions-by-topic --topic-arn <arn> --query 'Subscriptions[].{Protocol:Protocol,Endpoint:Endpoint,Status:SubscriptionArn}' aws sns get-topic-attributes --topic-arn <arn> --query 'Attributes.{Policy:Policy,DisplayName:DisplayName}'
publish from the CLI is the fastest way to test an event-driven pipeline end-to-end without writing code. list-subscriptions-by-topic shows what's actually consuming: subscription ARN as PendingConfirmation means the endpoint never confirmed, a common silent failure for HTTP endpoints.
ecr data / platform
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 describe-repositories --query 'repositories[].{Name:repositoryName,URI:repositoryUri}' --output table aws ecr list-images --repository-name myrepo --filter tagStatus=UNTAGGED --query 'imageIds[].imageDigest' --output text aws ecr describe-image-scan-findings --repository-name myrepo --image-id imageTag=latest --query 'imageScanFindings.findings[?severity==`CRITICAL`].[name,description,uri]' --output table aws ecr batch-delete-image --repository-name myrepo --image-ids imageTag=old-tag
The get-login-password | docker login pipeline is the correct ECR auth pattern: token is valid for 12h, no stored credentials. Untagged image accumulation inflates storage costs; the list + delete pipeline cleans them. describe-image-scan-findings gives native ECR scan results. Use trivy for deeper analysis.
rds data / platform
aws rds describe-db-instances --query 'DBInstances[].{ID:DBInstanceIdentifier,Class:DBInstanceClass,Engine:Engine,Status:DBInstanceStatus,Endpoint:Endpoint.Address}' --output table aws rds create-db-snapshot --db-instance-identifier mydb --db-snapshot-identifier mydb-$(date +%Y%m%d) aws rds describe-db-log-files --db-instance-identifier mydb --query 'DescribeDBLogFiles[].{Name:LogFileName,Size:Size}' --output table aws rds download-db-log-file-portion --db-instance-identifier mydb --log-file-name error/postgresql.log --starting-token 0 --output text aws rds failover-db-cluster --db-cluster-identifier mycluster
Manual snapshot before schema migrations, not a substitute for automated backups but a cheap safety net with a human-readable name. download-db-log-file-portion pulls Postgres/MySQL error logs without needing SSH or CloudWatch Logs agent. failover-db-cluster is a planned AZ failover. Test it before you need it under pressure.
eventbridge data / platform
aws events list-rules --query 'Rules[].{Name:Name,State:State,Schedule:ScheduleExpression,Pattern:EventPattern}' --output table aws events disable-rule --name MyScheduledRule aws events enable-rule --name MyScheduledRule aws events put-events --entries '[{"Source":"myapp","DetailType":"test","Detail":"{\"key\":\"value\"}","EventBusName":"default"}]' aws events list-targets-by-rule --rule MyRule --query 'Targets[].{ID:Id,ARN:Arn}'
disable-rule/enable-rule is the fastest way to pause a scheduled job during an incident without touching Terraform state. put-events injects a test event into the bus: the correct way to test rule patterns and target routing before a real event fires. list-targets-by-rule reveals what a rule actually invokes.
cloudformation (inspection) data / platform
aws cloudformation list-stacks --stack-status-filter UPDATE_ROLLBACK_FAILED CREATE_FAILED --query 'StackSummaries[].{Name:StackName,Status:StackStatus,Reason:StackStatusReason}' --output table aws cloudformation describe-stack-events --stack-name mystack --query 'StackEvents[?ResourceStatus==`UPDATE_FAILED`].{Resource:LogicalResourceId,Reason:ResourceStatusReason,Time:Timestamp}' aws cloudformation detect-stack-drift --stack-name mystack aws cloudformation describe-stack-resource-drifts --stack-name mystack --stack-resource-drift-status-filters MODIFIED DELETED --query 'StackResourceDrifts[].{Resource:LogicalResourceId,Status:StackResourceDriftStatus,Diff:PropertyDifferences}'
Inspection only: deploy via Terraform or the CDK, not the CLI. describe-stack-events filtered to UPDATE_FAILED is the fastest way to find the root cause of a stuck rollback. Drift detection surfaces manual console changes that diverge from the template. Run it before assuming a stack is clean.
No entries match this filter.