Home / Topics / AWS for DevOps / Cheatsheet
AWS for DevOps

Cheatsheet

Dense CLI and config reference for day-to-day AWS work and interviews. AWS CLI v2 syntax.


CLI setup, identity and output

TaskCommand
Configure SSO profileaws configure sso
Log in to SSOaws sso login --profile dev
Who am Iaws sts get-caller-identity
Use a profile for one commandaws s3 ls --profile dev
Set Region for the shellexport AWS_DEFAULT_REGION=ap-south-1
List enabled Regionsaws ec2 describe-regions --query 'Regions[].RegionName' --output text
List AZsaws ec2 describe-availability-zones --query 'AvailabilityZones[].ZoneName'
Output formats--output json|text|table|yaml
Filter client-side (JMESPath)--query 'Reservations[].Instances[].[InstanceId,State.Name]'
Filter server-side--filters Name=tag:Project,Values=ha-web
Paginate manually--max-items 50 --starting-token <token>
Wait for a stateaws ec2 wait instance-running --instance-ids i-...
Dry run permission checkaws ec2 run-instances ... --dry-run
Generate a skeleton inputaws ec2 run-instances --generate-cli-skeleton > in.json
Debug a callaws s3 ls --debug 2>&1 | head

Credential order: command-line flags, environment variables, assume-role/SSO profile, container credentials, instance profile (IMDS). Check aws configure list to see which source won.

EC2 and AMIs

TaskCommand
Latest AL2023 AMIaws ssm get-parameter --name /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 --query Parameter.Value --output text
Launch an instanceaws ec2 run-instances --image-id ami-... --instance-type t3.micro --subnet-id subnet-... --security-group-ids sg-... --iam-instance-profile Name=prof --metadata-options HttpTokens=required
List running instancesaws ec2 describe-instances --filters Name=instance-state-name,Values=running --query 'Reservations[].Instances[].[InstanceId,PrivateIpAddress,Tags[?Key==Name]|[0].Value]' --output table
Stop, start, terminateaws ec2 stop-instances --instance-ids i-... / start-instances / terminate-instances
Console output (boot errors)aws ec2 get-console-output --instance-id i-... --output text
Status checksaws ec2 describe-instance-status --instance-ids i-... --include-all-instances
Create an AMIaws ec2 create-image --instance-id i-... --name app-v1 --no-reboot
Copy AMI across Regionsaws ec2 copy-image --source-image-id ami-... --source-region ap-south-1 --region us-east-1 --name app-v1
Change instance typestop, then aws ec2 modify-instance-attribute --instance-id i-... --instance-type Value=t3.large
Read user dataaws ec2 describe-instance-attribute --instance-id i-... --attribute userData
Snapshot a volumeaws ec2 create-snapshot --volume-id vol-... --description "pre-change"
Unattached volumesaws ec2 describe-volumes --filters Name=status,Values=available --query 'Volumes[].[VolumeId,Size]'

IMDSv2 from inside an instance:

bash
TOKEN=$(curl -sX PUT http://169.254.169.254/latest/api/token -H "X-aws-ec2-metadata-token-ttl-seconds: 300")
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/instance-id
curl -s -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/

VPC networking

TaskCommand
Create VPCaws ec2 create-vpc --cidr-block 10.0.0.0/16
Create subnetaws ec2 create-subnet --vpc-id vpc-... --cidr-block 10.0.1.0/24 --availability-zone ap-south-1a
Internet gatewayaws ec2 create-internet-gateway then attach-internet-gateway --internet-gateway-id igw-... --vpc-id vpc-...
Default route to IGWaws ec2 create-route --route-table-id rtb-... --destination-cidr-block 0.0.0.0/0 --gateway-id igw-...
NAT gatewayaws ec2 create-nat-gateway --subnet-id subnet-pub --allocation-id eipalloc-...
Security group rule from SGaws ec2 authorize-security-group-ingress --group-id sg-app --ip-permissions "IpProtocol=tcp,FromPort=80,ToPort=80,UserIdGroupPairs=[{GroupId=sg-alb}]"
Remove a ruleaws ec2 revoke-security-group-ingress --group-id sg-... --protocol tcp --port 22 --cidr 0.0.0.0/0
S3 gateway endpointaws ec2 create-vpc-endpoint --vpc-id vpc-... --service-name com.amazonaws.ap-south-1.s3 --route-table-ids rtb-...
Interface endpointaws ec2 create-vpc-endpoint --vpc-id vpc-... --vpc-endpoint-type Interface --service-name com.amazonaws.ap-south-1.ssm --subnet-ids subnet-... --security-group-ids sg-... --private-dns-enabled
VPC peeringaws ec2 create-vpc-peering-connection --vpc-id vpc-a --peer-vpc-id vpc-b then accept and add routes both ways
Flow logs to CloudWatchaws ec2 create-flow-logs --resource-type VPC --resource-ids vpc-... --traffic-type ALL --log-group-name vpc-flow --deliver-logs-permission-arn arn:aws:iam::<acct>:role/flowlogs
Reachability analysisaws ec2 create-network-insights-path --source i-... --destination i-... --protocol tcp --destination-port 443

Security group versus NACL:

Security groupNetwork ACL
LevelNetwork interfaceSubnet
StateStatefulStateless
RulesAllow onlyAllow and deny, numbered
EvaluationAll rulesFirst match by rule number
DefaultDeny in, allow outDefault NACL allows all

Private subnets that need to reach AWS APIs: NAT gateway, or VPC endpoints (gateway for S3 and DynamoDB, interface for most others).

IAM and STS

TaskCommand
Create roleaws iam create-role --role-name r --assume-role-policy-document file://trust.json
Attach managed policyaws iam attach-role-policy --role-name r --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess
Inline policyaws iam put-role-policy --role-name r --policy-name p --policy-document file://p.json
Instance profileaws iam create-instance-profile --instance-profile-name p and add-role-to-instance-profile
Assume a roleaws sts assume-role --role-arn arn:aws:iam::<acct>:role/r --role-session-name s
Test a policyaws iam simulate-principal-policy --policy-source-arn <arn> --action-names s3:GetObject --resource-arns arn:aws:s3:::b/k
Last used infoaws iam get-role --role-name r --query Role.RoleLastUsed
Credential reportaws iam generate-credential-report then aws iam get-credential-report
Old access keysaws iam list-access-keys --user-name u and get-access-key-last-used --access-key-id AKIA...
Decode an auth erroraws sts decode-authorization-message --encoded-message <msg>
Policy versionsaws iam list-policy-versions --policy-arn <arn>

Evaluation order: explicit deny, then SCP, resource policy (same account), permission boundary, session policy, identity policy; default is deny. Cross-account needs an allow on both sides.

Temporary credentials from assume-role into the shell:

bash
creds=$(aws sts assume-role --role-arn "$ROLE_ARN" --role-session-name lab --query Credentials --output json)
export AWS_ACCESS_KEY_ID=$(jq -r .AccessKeyId <<<"$creds")
export AWS_SECRET_ACCESS_KEY=$(jq -r .SecretAccessKey <<<"$creds")
export AWS_SESSION_TOKEN=$(jq -r .SessionToken <<<"$creds")

ELB and Auto Scaling

TaskCommand
Create ALBaws elbv2 create-load-balancer --name alb --type application --subnets s1 s2 --security-groups sg-...
Target groupaws elbv2 create-target-group --name tg --protocol HTTP --port 80 --vpc-id vpc-... --health-check-path /health
Listeneraws elbv2 create-listener --load-balancer-arn <arn> --protocol HTTP --port 80 --default-actions Type=forward,TargetGroupArn=<tg>
HTTPS listener--protocol HTTPS --port 443 --certificates CertificateArn=<acm-arn> --ssl-policy ELBSecurityPolicy-TLS13-1-2-2021-06
Path ruleaws elbv2 create-rule --listener-arn <arn> --priority 10 --conditions Field=path-pattern,Values='/api/*' --actions Type=forward,TargetGroupArn=<tg2>
Target healthaws elbv2 describe-target-health --target-group-arn <tg>
Deregistration delayaws elbv2 modify-target-group-attributes --target-group-arn <tg> --attributes Key=deregistration_delay.timeout_seconds,Value=30
Create launch templateaws ec2 create-launch-template --launch-template-name lt --launch-template-data file://lt.json
New template versionaws ec2 create-launch-template-version --launch-template-name lt --source-version 1 --launch-template-data file://v2.json
Create ASGaws autoscaling create-auto-scaling-group --auto-scaling-group-name asg --launch-template LaunchTemplateName=lt,Version='$Latest' --min-size 2 --max-size 4 --vpc-zone-identifier "s1,s2" --target-group-arns <tg> --health-check-type ELB --health-check-grace-period 180
Target trackingaws autoscaling put-scaling-policy --auto-scaling-group-name asg --policy-name cpu --policy-type TargetTrackingScaling --target-tracking-configuration file://tt.json
Scheduled actionaws autoscaling put-scheduled-update-group-action --auto-scaling-group-name asg --scheduled-action-name day --recurrence "0 9 * * 1-5" --min-size 4
Rolling deployaws autoscaling start-instance-refresh --auto-scaling-group-name asg --preferences '{"MinHealthyPercentage":50,"InstanceWarmup":120}'
Cancel refreshaws autoscaling cancel-instance-refresh --auto-scaling-group-name asg
Protect an instanceaws autoscaling set-instance-protection --auto-scaling-group-name asg --instance-ids i-... --protected-from-scale-in
Take out of service for debuggingaws autoscaling enter-standby --auto-scaling-group-name asg --instance-ids i-... --should-decrement-desired-capacity
Scaling historyaws autoscaling describe-scaling-activities --auto-scaling-group-name asg

ALB versus NLB: ALB is layer 7 with host, path, header and query routing, WebSockets, gRPC, and no static IP. NLB is layer 4 with TCP, UDP and TLS, static or Elastic IPs per AZ, preserves the client source IP, and handles millions of requests per second. Gateway Load Balancer fronts virtual appliances.

ALB error codes: 502 bad response from target or closed connection, 503 no healthy targets, 504 target did not respond within the idle timeout, 460 client closed the connection, 463 too many X-Forwarded-For addresses.

RDS

TaskCommand
Describe instanceaws rds describe-db-instances --db-instance-identifier db
Create Multi-AZaws rds create-db-instance --db-instance-identifier db --engine postgres --db-instance-class db.t4g.micro --allocated-storage 20 --master-username admin --manage-master-user-password --multi-az --no-publicly-accessible --db-subnet-group-name sg --vpc-security-group-ids sg-...
Force failoveraws rds reboot-db-instance --db-instance-identifier db --force-failover
Read replicaaws rds create-db-instance-read-replica --db-instance-identifier db-r1 --source-db-instance-identifier db
Promote replicaaws rds promote-read-replica --db-instance-identifier db-r1
Manual snapshotaws rds create-db-snapshot --db-instance-identifier db --db-snapshot-identifier db-pre-change
Restore to a new instanceaws rds restore-db-instance-from-db-snapshot --db-instance-identifier db-restored --db-snapshot-identifier db-pre-change
Point in time restoreaws rds restore-db-instance-to-point-in-time --source-db-instance-identifier db --target-db-instance-identifier db-pit --restore-time 2026-01-01T10:00:00Z
Modify nowaws rds modify-db-instance --db-instance-identifier db --db-instance-class db.m6g.large --apply-immediately
Recent eventsaws rds describe-events --source-type db-instance --source-identifier db --duration 60
Logsaws rds describe-db-log-files --db-instance-identifier db
Enable deletion protectionaws rds modify-db-instance --db-instance-identifier db --deletion-protection

Key metrics: CPUUtilization, FreeableMemory, FreeStorageSpace, DatabaseConnections, ReadLatency, WriteLatency, ReplicaLag, BurstBalance (gp2), DiskQueueDepth.

Multi-AZ instance deployment: synchronous standby, same endpoint, failover about 60 to 120 seconds, standby not readable. Multi-AZ DB cluster (two readable standbys) fails over faster. Read replicas: asynchronous, readable, can be cross-Region, promotable.

S3

TaskCommand
Create bucket (non us-east-1)aws s3api create-bucket --bucket b --create-bucket-configuration LocationConstraint=ap-south-1
Block public accessaws s3api put-public-access-block --bucket b --public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
Versioningaws s3api put-bucket-versioning --bucket b --versioning-configuration Status=Enabled
Sync a folderaws s3 sync ./dist s3://b/ --delete
Copy with storage classaws s3 cp f s3://b/f --storage-class STANDARD_IA
Presigned URLaws s3 presign s3://b/f --expires-in 3600
List object versionsaws s3api list-object-versions --bucket b --prefix key
Lifecycleaws s3api put-bucket-lifecycle-configuration --bucket b --lifecycle-configuration file://lc.json
Bucket policyaws s3api put-bucket-policy --bucket b --policy file://p.json
Replicationaws s3api put-bucket-replication --bucket b --replication-configuration file://repl.json
Size of a bucketaws s3 ls s3://b --recursive --summarize --human-readable | tail -2
Empty and deleteaws s3 rm s3://b --recursive then aws s3api delete-bucket --bucket b

Storage classes: Standard, Intelligent-Tiering, Standard-IA, One Zone-IA, Glacier Instant Retrieval, Glacier Flexible Retrieval, Glacier Deep Archive. Default encryption is SSE-S3; choose SSE-KMS for key-level audit and control. S3 is strongly consistent for reads after writes and lists.

CloudFront and Route 53

TaskCommand
Create OACaws cloudfront create-origin-access-control --origin-access-control-config Name=oac,SigningProtocol=sigv4,SigningBehavior=always,OriginAccessControlOriginType=s3
Create distributionaws cloudfront create-distribution --distribution-config file://cf.json
Invalidate cacheaws cloudfront create-invalidation --distribution-id E... --paths "/index.html" "/static/*"
Wait until deployedaws cloudfront wait distribution-deployed --id E...
Get config and ETagaws cloudfront get-distribution-config --id E...
List hosted zonesaws route53 list-hosted-zones
Change recordsaws route53 change-resource-record-sets --hosted-zone-id Z... --change-batch file://change.json
List recordsaws route53 list-resource-record-sets --hosted-zone-id Z...
Health checkaws route53 create-health-check --caller-reference $(date +%s) --health-check-config Type=HTTP,FullyQualifiedDomainName=x.com,ResourcePath=/health
Test a recordaws route53 test-dns-answer --hosted-zone-id Z... --record-name x.com --record-type A

Managed cache policy IDs: 658327ea-f89d-4fab-a63d-7e88639e58f6 is CachingOptimized, 4135ea2d-6df8-44a3-9df3-4b5a84be39ad is CachingDisabled. CloudFront certificates must live in us-east-1.

Alias record skeleton:

json
{"Changes":[{"Action":"UPSERT","ResourceRecordSet":{"Name":"app.example.com","Type":"A",
 "AliasTarget":{"HostedZoneId":"<ALB CanonicalHostedZoneId>","DNSName":"dualstack.<alb-dns>","EvaluateTargetHealth":true}}}]}

Routing policies: simple, weighted, latency, failover, geolocation, geoproximity, multivalue answer, IP-based. Aliases to AWS resources are free and allowed at the zone apex; a CNAME is not allowed at the apex.

CloudWatch, SNS and CloudTrail

TaskCommand
Put metric alarmaws cloudwatch put-metric-alarm --alarm-name a --namespace AWS/EC2 --metric-name CPUUtilization --dimensions Name=InstanceId,Value=i-... --statistic Average --period 60 --evaluation-periods 3 --threshold 80 --comparison-operator GreaterThanThreshold --alarm-actions <sns-arn>
List alarms in ALARMaws cloudwatch describe-alarms --state-value ALARM
Test an alarmaws cloudwatch set-alarm-state --alarm-name a --state-value ALARM --state-reason test
Read a metricaws cloudwatch get-metric-statistics --namespace AWS/EC2 --metric-name CPUUtilization --dimensions Name=InstanceId,Value=i-... --start-time 2026-01-01T00:00:00Z --end-time 2026-01-01T01:00:00Z --period 300 --statistics Average
Tail logsaws logs tail /aws/app --follow --since 10m
Log retentionaws logs put-retention-policy --log-group-name /aws/app --retention-in-days 14
Logs Insightsaws logs start-query --log-group-name /aws/app --start-time <epoch> --end-time <epoch> --query-string 'fields @timestamp, @message | filter @message like /ERROR/ | limit 20'
Metric filteraws logs put-metric-filter --log-group-name /aws/app --filter-name errors --filter-pattern ERROR --metric-transformations metricName=Errors,metricNamespace=App,metricValue=1
Create SNS topicaws sns create-topic --name alerts
Subscribeaws sns subscribe --topic-arn <arn> --protocol email --notification-endpoint [email protected]
Publish a testaws sns publish --topic-arn <arn> --message "test"
Find an API callaws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=TerminateInstances
Create trailaws cloudtrail create-trail --name org-trail --s3-bucket-name <bucket> --is-multi-region-trail then start-logging

Useful metric names: AWS/ApplicationELB has HTTPCode_Target_5XX_Count, TargetResponseTime, UnHealthyHostCount, RequestCountPerTarget. AWS/EC2 has CPUUtilization, StatusCheckFailed. Memory and disk are not EC2 metrics; use the CloudWatch agent.

Systems Manager and Secrets

TaskCommand
Shell without SSHaws ssm start-session --target i-...
Port forward to a private hostaws ssm start-session --target i-... --document-name AWS-StartPortForwardingSessionToRemoteHost --parameters '{"host":["db.internal"],"portNumber":["5432"],"localPortNumber":["5433"]}'
Run a command on instancesaws ssm send-command --document-name AWS-RunShellScript --targets Key=tag:Project,Values=ha-web --parameters 'commands=["uptime"]'
Command outputaws ssm get-command-invocation --command-id <id> --instance-id i-...
Managed instancesaws ssm describe-instance-information --query 'InstanceInformationList[].[InstanceId,PingStatus]'
Put parameteraws ssm put-parameter --name /app/prod/db-host --type String --value x --overwrite
Secure parameteraws ssm put-parameter --name /app/prod/token --type SecureString --value x
Get parameteraws ssm get-parameter --name /app/prod/token --with-decryption --query Parameter.Value --output text
By pathaws ssm get-parameters-by-path --path /app/prod --recursive --with-decryption
Secret valueaws secretsmanager get-secret-value --secret-id <arn> --query SecretString --output text
Create secretaws secretsmanager create-secret --name app/prod/db --secret-string '{"user":"u","password":"p"}'
Rotateaws secretsmanager rotate-secret --secret-id app/prod/db

Cost and tagging

TaskCommand
Cost by serviceaws ce get-cost-and-usage --time-period Start=2026-01-01,End=2026-02-01 --granularity MONTHLY --metrics UnblendedCost --group-by Type=DIMENSION,Key=SERVICE
Cost by tagaws ce get-cost-and-usage --time-period Start=...,End=... --granularity DAILY --metrics UnblendedCost --group-by Type=TAG,Key=Project
Forecastaws ce get-cost-forecast --time-period Start=...,End=... --metric UNBLENDED_COST --granularity MONTHLY
Activate cost tagaws ce update-cost-allocation-tags-status --cost-allocation-tags-status TagKey=Project,Status=Active --region us-east-1
Resources by tagaws resourcegroupstaggingapi get-resources --tag-filters Key=Project,Values=ha-web
Create budgetaws budgets create-budget --account-id <id> --budget file://b.json --notifications-with-subscribers file://n.json
Rightsizingaws compute-optimizer get-ec2-instance-recommendations

Where the money usually leaks: NAT gateway hourly and per-GB, cross-AZ and internet data transfer, idle ALBs and NAT gateways, unattached EBS volumes and old snapshots, oversized RDS, CloudWatch Logs without retention, public IPv4 addresses (charged hourly).

Policy snippets

Least-privilege S3 read of one prefix:

json
{"Version":"2012-10-17","Statement":[
 {"Effect":"Allow","Action":"s3:GetObject","Resource":"arn:aws:s3:::my-bucket/reports/*"},
 {"Effect":"Allow","Action":"s3:ListBucket","Resource":"arn:aws:s3:::my-bucket",
  "Condition":{"StringLike":{"s3:prefix":["reports/*"]}}}]}

Trust policy for EC2:

json
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"ec2.amazonaws.com"},"Action":"sts:AssumeRole"}]}

Deny everything over plain HTTP on a bucket:

json
{"Effect":"Deny","Principal":"*","Action":"s3:*","Resource":["arn:aws:s3:::my-bucket","arn:aws:s3:::my-bucket/*"],
 "Condition":{"Bool":{"aws:SecureTransport":"false"}}}

Cross-account trust with external ID:

json
{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::111111111111:root"},"Action":"sts:AssumeRole",
 "Condition":{"StringEquals":{"sts:ExternalId":"lab-1234"}}}

Require MFA for a sensitive action:

json
{"Effect":"Deny","Action":"ec2:TerminateInstances","Resource":"*",
 "Condition":{"BoolIfExists":{"aws:MultiFactorAuthPresent":"false"}}}

Numbers worth remembering

ItemValue
Default VPCs per Region quota5 (adjustable)
Security groups per network interface5 default (adjustable up to 16)
Rules per security group60 inbound, 60 outbound default
Reserved IPs per subnet5 (first four and the last)
Smallest and largest VPC CIDR/28 to /16
ALB idle timeout default60 seconds
ALB target health defaultsinterval 30 s, healthy 5, unhealthy 2
ASG default cooldown300 seconds
RDS Multi-AZ failovertypically 60 to 120 seconds
S3 single PUT limit, max object5 GB, 5 TB
S3 durability, Standard availability11 nines, 99.99 percent
CloudFront invalidationfirst 1,000 paths a month free
Lambda max duration15 minutes
CloudTrail event history90 days of management events
STS assume-role session1 hour default, up to the role maximum (up to 12 hours)
Route 53 SLA100 percent

Quotas change. Check Service Quotas when it matters: aws service-quotas list-service-quotas --service-code vpc.

Top 15 interview one-liners

  1. A Region is a geographic area with multiple AZs; AZs give high availability, Regions give disaster recovery.
  2. A subnet is public only because its route table sends 0.0.0.0/0 to an internet gateway.
  3. Security groups are stateful allow-lists on interfaces; NACLs are stateless numbered allow and deny rules on subnets.
  4. Use roles, not access keys, for workloads: instance profiles on EC2, task roles on ECS, IRSA or Pod Identity on EKS.
  5. IAM evaluation: explicit deny always wins, then something must explicitly allow; the default is deny.
  6. An ASG with --health-check-type ELB replaces instances that fail the load balancer check, not just dead hosts.
  7. ALB is layer 7 with path and host routing; NLB is layer 4 with static IPs and the client source IP preserved.
  8. RDS Multi-AZ is for availability (sync standby, same endpoint, 60 to 120 second failover); read replicas are for scale and cross-Region DR.
  9. Keep S3 private with Block Public Access and let CloudFront read it through Origin Access Control scoped to one distribution ARN.
  10. Route 53 alias records to ALB or CloudFront are free, work at the apex, and follow the target's addresses.
  11. Alarm on symptoms users feel (5xx, latency, unhealthy hosts), not only on CPU.
  12. CloudTrail tells you who did what; CloudWatch tells you what the system is doing; Config tells you how it changed.
  13. Private subnets need a NAT gateway or VPC endpoints to reach AWS APIs; gateway endpoints for S3 and DynamoDB are free.
  14. The big surprise bills are NAT data processing, cross-AZ and internet transfer, idle load balancers and unattached volumes. Tag and budget from day one.
  15. Never put secrets in user data or AMIs; read them at runtime from Secrets Manager or Parameter Store using the instance role.
Feedback