Introduction
The AWS Command Line Interface (CLI) is a unified tool to manage your AWS services from the terminal. With just one tool to download and configure, you can control multiple AWS services from the command line and automate them through scripts. This cheat sheet provides a quick reference for the most commonly used AWS CLI commands organized by service.
Installation and Configuration
Installation
# Install on Linux/macOS using pip
pip install awscli --upgrade --user
# Install on Windows using MSI installer
# Download from: https://aws.amazon.com/cli/
# Verify installation
aws --version
Configuration
# Configure AWS CLI with your credentials
aws configure
# Configure specific profile
aws configure --profile profilename
# List configured profiles
aws configure list-profiles
# Use a specific profile
aws s3 ls --profile profilename
# Set AWS region
aws configure set region us-west-2
# Set output format (json, yaml, text, table)
aws configure set output json
Global Options
--profile PROFILE # Use a specific profile from your credentials file
--region REGION # The region to use (e.g., us-west-2)
--output FORMAT # The output format (json, yaml, text, table)
--query QUERY # JMESPath query to filter output
--debug # Turn on debug logging
--no-verify-ssl # Disable SSL verification
--endpoint-url URL # Override AWS endpoint URL
--cli-read-timeout SEC # Max socket read time in seconds
--cli-connect-timeout # Max socket connect time in seconds
EC2 (Elastic Compute Cloud)
Instances
# List all instances
aws ec2 describe-instances
# List instances with specific filter
aws ec2 describe-instances --filters "Name=instance-type,Values=t2.micro"
# List only running instances
aws ec2 describe-instances --filters "Name=instance-state-name,Values=running"
# Get specific instances by ID
aws ec2 describe-instances --instance-ids i-1234567890abcdef0
# Start an instance
aws ec2 start-instances --instance-ids i-1234567890abcdef0
# Stop an instance
aws ec2 stop-instances --instance-ids i-1234567890abcdef0
# Terminate an instance
aws ec2 terminate-instances --instance-ids i-1234567890abcdef0
# Create a new instance
aws ec2 run-instances --image-id ami-12345678 --count 1 --instance-type t2.micro --key-name MyKeyPair --security-group-ids sg-12345678
# Monitor instance status
aws ec2 describe-instance-status --instance-ids i-1234567890abcdef0
AMIs (Amazon Machine Images)
# List available AMIs owned by you
aws ec2 describe-images --owners self
# List Amazon-provided AMIs
aws ec2 describe-images --owners amazon
# Find AMIs by name pattern
aws ec2 describe-images --filters "Name=name,Values=amzn2-ami-hvm-*"
# Create an AMI from an instance
aws ec2 create-image --instance-id i-1234567890abcdef0 --name "My-Server-Backup" --description "Backup of my server"
# Deregister (delete) an AMI
aws ec2 deregister-image --image-id ami-12345678
Security Groups
# List all security groups
aws ec2 describe-security-groups
# Get details of a specific security group
aws ec2 describe-security-groups --group-ids sg-12345678
# Create a new security group
aws ec2 create-security-group --group-name MySecurityGroup --description "My security group" --vpc-id vpc-12345678
# Add inbound rule to security group
aws ec2 authorize-security-group-ingress --group-id sg-12345678 --protocol tcp --port 22 --cidr 203.0.113.0/24
# Add outbound rule to security group
aws ec2 authorize-security-group-egress --group-id sg-12345678 --protocol tcp --port 80 --cidr 0.0.0.0/0
# Delete a security group
aws ec2 delete-security-group --group-id sg-12345678
Key Pairs
# List all key pairs
aws ec2 describe-key-pairs
# Create a new key pair and save private key to file
aws ec2 create-key-pair --key-name MyKeyPair --query 'KeyMaterial' --output text > MyKeyPair.pem
# Import an existing public key
aws ec2 import-key-pair --key-name MyKeyPair --public-key-material fileb://~/path/to/public_key.pub
# Delete a key pair
aws ec2 delete-key-pair --key-name MyKeyPair
EBS (Elastic Block Store)
# List all EBS volumes
aws ec2 describe-volumes
# Create a new EBS volume
aws ec2 create-volume --size 8 --availability-zone us-west-2a --volume-type gp2
# Attach volume to instance
aws ec2 attach-volume --volume-id vol-12345678 --instance-id i-1234567890abcdef0 --device /dev/sdf
# Detach volume from instance
aws ec2 detach-volume --volume-id vol-12345678
# Create snapshot of a volume
aws ec2 create-snapshot --volume-id vol-12345678 --description "My volume backup"
# List all snapshots
aws ec2 describe-snapshots --owner-ids self
# Delete a volume
aws ec2 delete-volume --volume-id vol-12345678
# Delete a snapshot
aws ec2 delete-snapshot --snapshot-id snap-12345678
S3 (Simple Storage Service)
Buckets
# List all buckets
aws s3 ls
# Create a new bucket
aws s3 mb s3://my-bucket-name
# Delete an empty bucket
aws s3 rb s3://my-bucket-name
# Delete bucket with all content
aws s3 rb s3://my-bucket-name --force
# Enable versioning on a bucket
aws s3api put-bucket-versioning --bucket my-bucket-name --versioning-configuration Status=Enabled
# Set bucket policy
aws s3api put-bucket-policy --bucket my-bucket-name --policy file://policy.json
Objects
# List objects in a bucket
aws s3 ls s3://my-bucket-name
# List objects with details
aws s3 ls s3://my-bucket-name --recursive --human-readable --summarize
# Upload a file to S3
aws s3 cp file.txt s3://my-bucket-name/
# Upload a file with public read access
aws s3 cp file.txt s3://my-bucket-name/ --acl public-read
# Download a file from S3
aws s3 cp s3://my-bucket-name/file.txt downloaded-file.txt
# Copy object between buckets
aws s3 cp s3://source-bucket/file.txt s3://destination-bucket/
# Move object (copy and delete original)
aws s3 mv file.txt s3://my-bucket-name/
# Delete an object
aws s3 rm s3://my-bucket-name/file.txt
# Delete multiple objects based on prefix
aws s3 rm s3://my-bucket-name/logs/ --recursive
# Sync local directory to S3
aws s3 sync local-dir/ s3://my-bucket-name/path/
# Sync S3 bucket to local directory
aws s3 sync s3://my-bucket-name/path/ local-dir/
# Generate pre-signed URL for private object (valid for 3600 seconds)
aws s3 presign s3://my-bucket-name/private-file.txt --expires-in 3600
IAM (Identity and Access Management)
Users
# List all users
aws iam list-users
# Create a new user
aws iam create-user --user-name johndoe
# Delete a user
aws iam delete-user --user-name johndoe
# Add user to group
aws iam add-user-to-group --user-name johndoe --group-name Developers
# Remove user from group
aws iam remove-user-from-group --user-name johndoe --group-name Developers
# List access keys for user
aws iam list-access-keys --user-name johndoe
# Create access key for user
aws iam create-access-key --user-name johndoe
# Delete access key
aws iam delete-access-key --user-name johndoe --access-key-id AKIAIOSFODNN7EXAMPLE
Groups
# List all groups
aws iam list-groups
# Create a new group
aws iam create-group --group-name Developers
# Delete a group
aws iam delete-group --group-name Developers
# List users in a group
aws iam get-group --group-name Developers
# Attach policy to group
aws iam attach-group-policy --group-name Developers --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess
# Detach policy from group
aws iam detach-group-policy --group-name Developers --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess
Roles
# List all roles
aws iam list-roles
# Create a new role (with trust policy)
aws iam create-role --role-name EC2Role --assume-role-policy-document file://trust-policy.json
# Delete a role
aws iam delete-role --role-name EC2Role
# Attach policy to role
aws iam attach-role-policy --role-name EC2Role --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess
# Detach policy from role
aws iam detach-role-policy --role-name EC2Role --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess
# List attached policies for a role
aws iam list-attached-role-policies --role-name EC2Role
Policies
# List all policies
aws iam list-policies
# Get policy details
aws iam get-policy --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess
# Create a policy
aws iam create-policy --policy-name MyPolicy --policy-document file://policy.json
# Delete a policy
aws iam delete-policy --policy-arn arn:aws:iam::123456789012:policy/MyPolicy
# Get policy version details
aws iam get-policy-version --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess --version-id v1
Lambda
# List all Lambda functions
aws lambda list-functions
# Create a new function (from zip file)
aws lambda create-function --function-name my-function \
--runtime nodejs18.x \
--role arn:aws:iam::123456789012:role/lambda-role \
--handler index.handler \
--zip-file fileb://function.zip
# Get function configuration
aws lambda get-function-configuration --function-name my-function
# Update function code
aws lambda update-function-code --function-name my-function --zip-file fileb://function.zip
# Update function configuration
aws lambda update-function-configuration --function-name my-function --timeout 30 --memory-size 256
# Invoke a function
aws lambda invoke --function-name my-function --payload '{"key":"value"}' output.txt
# Invoke a function and get logs
aws lambda invoke --function-name my-function --payload '{"key":"value"}' --log-type Tail \
--query 'LogResult' --output text | base64 -d
# Delete a function
aws lambda delete-function --function-name my-function
# List event source mappings
aws lambda list-event-source-mappings --function-name my-function
# Add permission to invoke from S3
aws lambda add-permission --function-name my-function \
--statement-id s3-trigger --action lambda:InvokeFunction \
--principal s3.amazonaws.com \
--source-arn arn:aws:s3:::my-bucket-name
CloudFormation
# List stacks
aws cloudformation list-stacks
# Create a new stack
aws cloudformation create-stack --stack-name MyStack --template-body file://template.yaml
# Create stack with parameters
aws cloudformation create-stack --stack-name MyStack \
--template-body file://template.yaml \
--parameters ParameterKey=KeyPairName,ParameterValue=MyKey
# Update stack
aws cloudformation update-stack --stack-name MyStack --template-body file://updated-template.yaml
# Describe stack events
aws cloudformation describe-stack-events --stack-name MyStack
# Describe stack resources
aws cloudformation describe-stack-resources --stack-name MyStack
# Get stack outputs
aws cloudformation describe-stacks --stack-name MyStack --query "Stacks[0].Outputs"
# Validate template
aws cloudformation validate-template --template-body file://template.yaml
# Delete stack
aws cloudformation delete-stack --stack-name MyStack
RDS (Relational Database Service)
# List all DB instances
aws rds describe-db-instances
# Create DB instance
aws rds create-db-instance \
--db-instance-identifier mydb \
--db-instance-class db.t3.micro \
--engine mysql \
--master-username admin \
--master-user-password secret99 \
--allocated-storage 20
# Get DB instance details
aws rds describe-db-instances --db-instance-identifier mydb
# Modify DB instance
aws rds modify-db-instance --db-instance-identifier mydb --backup-retention-period 7
# Create DB snapshot
aws rds create-db-snapshot --db-instance-identifier mydb --db-snapshot-identifier mydb-snapshot
# List all DB snapshots
aws rds describe-db-snapshots
# Restore DB from snapshot
aws rds restore-db-instance-from-db-snapshot \
--db-instance-identifier mydb-restored \
--db-snapshot-identifier mydb-snapshot
# Delete DB instance
aws rds delete-db-instance --db-instance-identifier mydb --skip-final-snapshot
# Delete DB instance with final snapshot
aws rds delete-db-instance \
--db-instance-identifier mydb \
--final-db-snapshot-identifier mydb-final-snapshot
Route 53
# List hosted zones
aws route53 list-hosted-zones
# Create hosted zone
aws route53 create-hosted-zone --name example.com --caller-reference 2023-05-07
# Get hosted zone details
aws route53 get-hosted-zone --id /hostedzone/Z1D633PJN98FT9
# List resource record sets in a hosted zone
aws route53 list-resource-record-sets --hosted-zone-id Z1D633PJN98FT9
# Create record set (using JSON input file)
aws route53 change-resource-record-sets --hosted-zone-id Z1D633PJN98FT9 --change-batch file://change-batch.json
# Delete hosted zone
aws route53 delete-hosted-zone --id /hostedzone/Z1D633PJN98FT9
CloudWatch
# List metrics
aws cloudwatch list-metrics
# Get metric statistics
aws cloudwatch get-metric-statistics \
--namespace AWS/EC2 \
--metric-name CPUUtilization \
--dimensions Name=InstanceId,Value=i-1234567890abcdef0 \
--start-time 2023-05-01T00:00:00Z \
--end-time 2023-05-07T00:00:00Z \
--period 3600 \
--statistics Average Maximum
# Put custom metric data
aws cloudwatch put-metric-data \
--namespace MyApplication \
--metric-name RequestCount \
--value 42 \
--dimensions Service=Backend,Region=us-west-2
# List alarms
aws cloudwatch describe-alarms
# Create alarm
aws cloudwatch put-metric-alarm \
--alarm-name cpu-high \
--alarm-description "CPU usage exceeds 70%" \
--metric-name CPUUtilization \
--namespace AWS/EC2 \
--dimensions Name=InstanceId,Value=i-1234567890abcdef0 \
--statistic Average \
--period 300 \
--threshold 70 \
--comparison-operator GreaterThanThreshold \
--evaluation-periods 2
# Delete alarm
aws cloudwatch delete-alarms --alarm-names cpu-high
# Get logs
aws logs get-log-events \
--log-group-name /aws/lambda/my-function \
--log-stream-name 2023/05/07/[$LATEST]abcdef1234567890 \
--start-time 1683417600000 \
--limit 100
SNS (Simple Notification Service)
# List topics
aws sns list-topics
# Create topic
aws sns create-topic --name my-topic
# List subscriptions
aws sns list-subscriptions
# Subscribe to topic (email)
aws sns subscribe \
--topic-arn arn:aws:sns:us-west-2:123456789012:my-topic \
--protocol email \
--notification-endpoint user@example.com
# Publish message to topic
aws sns publish \
--topic-arn arn:aws:sns:us-west-2:123456789012:my-topic \
--message "Hello from SNS" \
--subject "Test Message"
# Unsubscribe
aws sns unsubscribe --subscription-arn arn:aws:sns:us-west-2:123456789012:my-topic:abcdef12-3456-7890-abcd-ef1234567890
# Delete topic
aws sns delete-topic --topic-arn arn:aws:sns:us-west-2:123456789012:my-topic
SQS (Simple Queue Service)
# List queues
aws sqs list-queues
# Create queue
aws sqs create-queue --queue-name my-queue
# Get queue URL
aws sqs get-queue-url --queue-name my-queue
# Send message to queue
aws sqs send-message \
--queue-url https://sqs.us-west-2.amazonaws.com/123456789012/my-queue \
--message-body "Hello from SQS"
# Receive messages from queue
aws sqs receive-message \
--queue-url https://sqs.us-west-2.amazonaws.com/123456789012/my-queue \
--max-number-of-messages 10
# Delete message from queue
aws sqs delete-message \
--queue-url https://sqs.us-west-2.amazonaws.com/123456789012/my-queue \
--receipt-handle AQEB...
# Purge queue
aws sqs purge-queue --queue-url https://sqs.us-west-2.amazonaws.com/123456789012/my-queue
# Delete queue
aws sqs delete-queue --queue-url https://sqs.us-west-2.amazonaws.com/123456789012/my-queue
DynamoDB
# List tables
aws dynamodb list-tables
# Create table
aws dynamodb create-table \
--table-name Users \
--attribute-definitions AttributeName=UserId,AttributeType=S \
--key-schema AttributeName=UserId,KeyType=HASH \
--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5
# Describe table
aws dynamodb describe-table --table-name Users
# Put item
aws dynamodb put-item \
--table-name Users \
--item '{"UserId": {"S": "user123"}, "Name": {"S": "John Doe"}, "Email": {"S": "john@example.com"}}'
# Get item
aws dynamodb get-item \
--table-name Users \
--key '{"UserId": {"S": "user123"}}'
# Update item
aws dynamodb update-item \
--table-name Users \
--key '{"UserId": {"S": "user123"}}' \
--update-expression "SET Email = :email" \
--expression-attribute-values '{":email": {"S": "newemail@example.com"}}' \
--return-values ALL_NEW
# Query table
aws dynamodb query \
--table-name Users \
--key-condition-expression "UserId = :id" \
--expression-attribute-values '{":id": {"S": "user123"}}'
# Scan table
aws dynamodb scan --table-name Users
# Delete item
aws dynamodb delete-item \
--table-name Users \
--key '{"UserId": {"S": "user123"}}'
# Delete table
aws dynamodb delete-table --table-name Users
ECS (Elastic Container Service)
# List clusters
aws ecs list-clusters
# Create cluster
aws ecs create-cluster --cluster-name my-cluster
# List task definitions
aws ecs list-task-definitions
# Register task definition (using JSON file)
aws ecs register-task-definition --cli-input-json file://task-definition.json
# List services in a cluster
aws ecs list-services --cluster my-cluster
# Create service
aws ecs create-service \
--cluster my-cluster \
--service-name my-service \
--task-definition my-task:1 \
--desired-count 2
# Update service
aws ecs update-service \
--cluster my-cluster \
--service my-service \
--task-definition my-task:2 \
--desired-count 3
# Run task
aws ecs run-task \
--cluster my-cluster \
--task-definition my-task:1 \
--count 1
# Stop task
aws ecs stop-task --cluster my-cluster --task arn:aws:ecs:region:account-id:task/task-id
# Delete service
aws ecs delete-service --cluster my-cluster --service my-service --force
# Delete cluster
aws ecs delete-cluster --cluster my-cluster
Useful Tips
Use Output Filtering:
# Get only instance IDs aws ec2 describe-instances --query 'Reservations[*].Instances[*].InstanceId' --output text # Get only specific attributes aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId,State.Name,InstanceType]' --output tableUse AWS CLI Pagination:
# Limit number of items returned aws s3api list-objects --bucket my-bucket --max-items 100 # Get next batch of results using token aws s3api list-objects --bucket my-bucket --starting-token eyJNYXJrZXIiOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiAxMH0=Multiple AWS Profiles:
# Setup profiles in ~/.aws/config and ~/.aws/credentials aws s3 ls --profile prod aws ec2 describe-instances --profile devAutomate With Shell Scripts:
#!/bin/bash # Backup all running instance IDs to a file aws ec2 describe-instances \ --filters "Name=instance-state-name,Values=running" \ --query 'Reservations[*].Instances[*].InstanceId' \ --output text > running-instances.txtDry Run Mode:
# Test an operation without performing it aws ec2 stop-instances --instance-ids i-1234567890abcdef0 --dry-run
