AWS CLI
Website: https://aws.amazon.com/cli/ CLI Tool: aws Authentication: AWS Access Keys, IAM roles
Description
The AWS Command Line Interface (CLI) is a unified tool to manage AWS services. Control multiple AWS services from the command line and automate them through scripts. Essential for cloud infrastructure management, DevOps, and automation tasks on Amazon Web Services.
Commands
Configuration
Configure Profile
aws configure
aws configure --profile production
aws configure list
Set up AWS credentials and default region interactively.
Set Credentials
aws configure set aws_access_key_id <key>
aws configure set aws_secret_access_key <secret>
aws configure set region us-east-1
aws configure set output json
Set individual configuration values.
Get Configuration
aws configure get aws_access_key_id
aws configure get region
aws configure get output --profile production
Retrieve configuration values.
List Profiles
aws configure list-profiles
List all configured profiles.
S3 (Simple Storage Service)
List Buckets
aws s3 ls
aws s3 ls s3://bucket-name/
aws s3 ls s3://bucket-name/prefix/ --recursive
List buckets or objects in bucket.
Copy Files
aws s3 cp file.txt s3://bucket-name/
aws s3 cp s3://bucket-name/file.txt .
aws s3 cp s3://source/file.txt s3://dest/file.txt
aws s3 cp folder/ s3://bucket-name/folder/ --recursive
Copy files to/from S3.
Sync Directories
aws s3 sync ./local s3://bucket-name/remote
aws s3 sync s3://bucket-name/remote ./local
aws s3 sync s3://source-bucket s3://dest-bucket
Sync directories with S3.
Move Files
aws s3 mv file.txt s3://bucket-name/
aws s3 mv s3://bucket-name/old.txt s3://bucket-name/new.txt
Move/rename files in S3.
Delete Files
aws s3 rm s3://bucket-name/file.txt
aws s3 rm s3://bucket-name/folder/ --recursive
Delete files from S3.
Create/Delete Bucket
aws s3 mb s3://new-bucket-name
aws s3 rb s3://bucket-name
aws s3 rb s3://bucket-name --force
Make or remove S3 buckets.
Presigned URL
aws s3 presign s3://bucket-name/file.txt
aws s3 presign s3://bucket-name/file.txt --expires-in 3600
Generate presigned URL for temporary access.
EC2 (Elastic Compute Cloud)
List Instances
aws ec2 describe-instances
aws ec2 describe-instances --instance-ids i-1234567890abcdef0
aws ec2 describe-instances --filters "Name=instance-state-name,Values=running"
List and describe EC2 instances.
Start/Stop Instances
aws ec2 start-instances --instance-ids i-1234567890abcdef0
aws ec2 stop-instances --instance-ids i-1234567890abcdef0
aws ec2 reboot-instances --instance-ids i-1234567890abcdef0
Control instance state.
Terminate Instance
aws ec2 terminate-instances --instance-ids i-1234567890abcdef0
Terminate EC2 instance.
Create Instance
aws ec2 run-instances \
--image-id ami-0abcdef1234567890 \
--instance-type t2.micro \
--key-name my-key-pair \
--security-group-ids sg-903004f8 \
--subnet-id subnet-6e7f829e
Launch new EC2 instance.
Security Groups
aws ec2 describe-security-groups
aws ec2 create-security-group --group-name my-sg --description "My security group"
aws ec2 authorize-security-group-ingress --group-id sg-903004f8 --protocol tcp --port 22 --cidr 0.0.0.0/0
Manage security groups.
Key Pairs
aws ec2 describe-key-pairs
aws ec2 create-key-pair --key-name my-key --query 'KeyMaterial' --output text > my-key.pem
aws ec2 delete-key-pair --key-name my-key
Manage SSH key pairs.
IAM (Identity and Access Management)
List Users
aws iam list-users
aws iam get-user --user-name username
List IAM users.
Create User
aws iam create-user --user-name newuser
aws iam create-access-key --user-name newuser
Create IAM user and access keys.
List Roles
aws iam list-roles
aws iam get-role --role-name rolename
List and describe IAM roles.
Attach Policy
aws iam attach-user-policy --user-name username --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess
aws iam attach-role-policy --role-name rolename --policy-arn arn:aws:iam::aws:policy/AmazonS3FullAccess
Attach policies to users or roles.
List Policies
aws iam list-policies
aws iam list-attached-user-policies --user-name username
List IAM policies.
Lambda
List Functions
aws lambda list-functions
aws lambda get-function --function-name my-function
List Lambda functions.
Invoke Function
aws lambda invoke --function-name my-function output.txt
aws lambda invoke --function-name my-function --payload '{"key":"value"}' output.txt
Invoke Lambda function.
Create Function
aws lambda create-function \
--function-name my-function \
--runtime python3.9 \
--role arn:aws:iam::123456789012:role/lambda-role \
--handler lambda_function.lambda_handler \
--zip-file fileb://function.zip
Create new Lambda function.
Update Function Code
aws lambda update-function-code \
--function-name my-function \
--zip-file fileb://function.zip
Update Lambda function code.
Delete Function
aws lambda delete-function --function-name my-function
Delete Lambda function.
RDS (Relational Database Service)
List DB Instances
aws rds describe-db-instances
aws rds describe-db-instances --db-instance-identifier mydb
List RDS database instances.
Create DB Instance
aws rds create-db-instance \
--db-instance-identifier mydb \
--db-instance-class db.t3.micro \
--engine postgres \
--master-username admin \
--master-user-password mypassword \
--allocated-storage 20
Create RDS database instance.
Create Snapshot
aws rds create-db-snapshot \
--db-instance-identifier mydb \
--db-snapshot-identifier mydb-snapshot
Create database snapshot.
Delete DB Instance
aws rds delete-db-instance \
--db-instance-identifier mydb \
--skip-final-snapshot
Delete RDS database instance.
CloudFormation
List Stacks
aws cloudformation list-stacks
aws cloudformation describe-stacks --stack-name my-stack
List CloudFormation stacks.
Create Stack
aws cloudformation create-stack \
--stack-name my-stack \
--template-body file://template.yaml \
--parameters ParameterKey=KeyName,ParameterValue=MyKey
Create CloudFormation stack.
Update Stack
aws cloudformation update-stack \
--stack-name my-stack \
--template-body file://template.yaml
Update existing stack.
Delete Stack
aws cloudformation delete-stack --stack-name my-stack
Delete CloudFormation stack.
ECS (Elastic Container Service)
List Clusters
aws ecs list-clusters
aws ecs describe-clusters --clusters my-cluster
List ECS clusters.
List Services
aws ecs list-services --cluster my-cluster
aws ecs describe-services --cluster my-cluster --services my-service
List services in cluster.
List Tasks
aws ecs list-tasks --cluster my-cluster
aws ecs describe-tasks --cluster my-cluster --tasks task-id
List running tasks.
Run Task
aws ecs run-task \
--cluster my-cluster \
--task-definition my-task:1 \
--count 1
Run ECS task.
CloudWatch
List Metrics
aws cloudwatch list-metrics
aws cloudwatch list-metrics --namespace AWS/EC2
List CloudWatch metrics.
Get Metric Statistics
aws cloudwatch get-metric-statistics \
--namespace AWS/EC2 \
--metric-name CPUUtilization \
--dimensions Name=InstanceId,Value=i-1234567890abcdef0 \
--start-time 2024-01-01T00:00:00Z \
--end-time 2024-01-02T00:00:00Z \
--period 3600 \
--statistics Average
Get metric data.
List Alarms
aws cloudwatch describe-alarms
aws cloudwatch describe-alarms --alarm-names my-alarm
List CloudWatch alarms.
Put Metric Data
aws cloudwatch put-metric-data \
--namespace MyApp \
--metric-name RequestCount \
--value 1
Publish custom metric data.
DynamoDB
List Tables
aws dynamodb list-tables
aws dynamodb describe-table --table-name my-table
List DynamoDB tables.
Get Item
aws dynamodb get-item \
--table-name my-table \
--key '{"id":{"S":"123"}}'
Retrieve item from table.
Put Item
aws dynamodb put-item \
--table-name my-table \
--item '{"id":{"S":"123"},"name":{"S":"John"}}'
Insert or update item.
Query
aws dynamodb query \
--table-name my-table \
--key-condition-expression "id = :id" \
--expression-attribute-values '{":id":{"S":"123"}}'
Query table with conditions.
Scan
aws dynamodb scan --table-name my-table
aws dynamodb scan --table-name my-table --filter-expression "age > :val" --expression-attribute-values '{":val":{"N":"18"}}'
Scan entire table.
Route53
List Hosted Zones
aws route53 list-hosted-zones
List Route53 hosted zones.
List Record Sets
aws route53 list-resource-record-sets --hosted-zone-id Z1234567890ABC
List DNS records in zone.
Change Record
aws route53 change-resource-record-sets \
--hosted-zone-id Z1234567890ABC \
--change-batch file://changes.json
Create/update/delete DNS records.
SQS (Simple Queue Service)
List Queues
aws sqs list-queues
aws sqs get-queue-url --queue-name my-queue
List SQS queues.
Send Message
aws sqs send-message \
--queue-url https://sqs.us-east-1.amazonaws.com/123456789012/my-queue \
--message-body "Hello World"
Send message to queue.
Receive Message
aws sqs receive-message \
--queue-url https://sqs.us-east-1.amazonaws.com/123456789012/my-queue
Receive messages from queue.
Delete Message
aws sqs delete-message \
--queue-url https://sqs.us-east-1.amazonaws.com/123456789012/my-queue \
--receipt-handle <receipt-handle>
Delete message from queue.
SNS (Simple Notification Service)
List Topics
aws sns list-topics
List SNS topics.
Create Topic
aws sns create-topic --name my-topic
Create SNS topic.
Publish Message
aws sns publish \
--topic-arn arn:aws:sns:us-east-1:123456789012:my-topic \
--message "Hello World"
Publish message to topic.
Subscribe
aws sns subscribe \
--topic-arn arn:aws:sns:us-east-1:123456789012:my-topic \
--protocol email \
--notification-endpoint user@example.com
Subscribe to topic.
General Options
Output Format
aws <command> --output json
aws <command> --output table
aws <command> --output text
aws <command> --output yaml
Specify output format.
Query Results
aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId,State.Name]'
aws s3api list-buckets --query 'Buckets[?contains(Name, `prod`)].Name'
Filter output using JMESPath queries.
Profile
aws <command> --profile production
aws <command> --profile dev
Use specific AWS profile.
Region
aws <command> --region us-west-2
aws <command> --region eu-west-1
Specify AWS region.
Debug
aws <command> --debug
aws <command> --no-verify-ssl
Enable debug output or skip SSL verification.
Examples
S3 Workflows
# Backup directory to S3
aws s3 sync ./backup s3://my-backup-bucket/$(date +%Y-%m-%d)/
# Download latest backup
aws s3 cp s3://my-backup-bucket/ ./restore/ --recursive
# Set bucket policy
aws s3api put-bucket-policy --bucket my-bucket --policy file://policy.json
# Enable versioning
aws s3api put-bucket-versioning --bucket my-bucket --versioning-configuration Status=Enabled
# List large files
aws s3api list-objects --bucket my-bucket --query "Contents[?Size > \`1048576\`].[Key,Size]" --output table
EC2 Management
# List running instances
aws ec2 describe-instances --filters "Name=instance-state-name,Values=running" --query 'Reservations[*].Instances[*].[InstanceId,InstanceType,State.Name]' --output table
# Get instance IP addresses
aws ec2 describe-instances --instance-ids i-1234567890abcdef0 --query 'Reservations[*].Instances[*].[PublicIpAddress,PrivateIpAddress]' --output text
# Create AMI from instance
aws ec2 create-image --instance-id i-1234567890abcdef0 --name "My AMI" --description "Created on $(date)"
# Stop all instances with tag
aws ec2 describe-instances --filters "Name=tag:Environment,Values=dev" --query 'Reservations[*].Instances[*].InstanceId' --output text | xargs aws ec2 stop-instances --instance-ids
Lambda Operations
# Deploy Lambda function
zip function.zip lambda_function.py
aws lambda update-function-code --function-name my-function --zip-file fileb://function.zip
# Set environment variables
aws lambda update-function-configuration --function-name my-function --environment Variables={KEY1=value1,KEY2=value2}
# View logs
aws logs tail /aws/lambda/my-function --follow
# Get function metrics
aws cloudwatch get-metric-statistics --namespace AWS/Lambda --metric-name Invocations --dimensions Name=FunctionName,Value=my-function --start-time $(date -u -d '1 hour ago' +%Y-%m-%dT%H:%M:%S) --end-time $(date -u +%Y-%m-%dT%H:%M:%S) --period 300 --statistics Sum
IAM Security
# Create user with programmatic access
aws iam create-user --user-name ci-user
aws iam create-access-key --user-name ci-user
# Attach read-only policy
aws iam attach-user-policy --user-name ci-user --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess
# List user permissions
aws iam list-attached-user-policies --user-name ci-user
aws iam list-user-policies --user-name ci-user
# Generate credential report
aws iam generate-credential-report
aws iam get-credential-report --output text | base64 -d > report.csv
Multi-Account Operations
# Assume role in another account
aws sts assume-role --role-arn arn:aws:iam::123456789012:role/CrossAccountRole --role-session-name my-session
# Use temporary credentials
export AWS_ACCESS_KEY_ID=<temporary-key>
export AWS_SECRET_ACCESS_KEY=<temporary-secret>
export AWS_SESSION_TOKEN=<session-token>
Notes
- Configuration: Stored in ~/.aws/config and ~/.aws/credentials
- Profiles: Use
--profileto switch between different AWS accounts - Regions: Default region in config, override with
--region - Output Formats: json, yaml, text, table
- Pagination: Use
--max-itemsand--starting-tokenfor large result sets - Filtering: Use
--filtersfor AWS-side filtering - Querying: Use
--querywith JMESPath for client-side filtering - Waiter Commands: Use
aws <service> waitto poll until resource ready - DryRun: Many commands support
--dry-runto test without executing - CLI Version: v1 (Python-based) and v2 (newer, compiled)
- Authentication: Access keys, IAM roles, SSO, MFA
- Environment Variables: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION
- Best Practices: Use IAM roles when possible, rotate access keys, use MFA
- Error Codes: Check exit code, use
--debugfor troubleshooting - Rate Limiting: AWS APIs have rate limits, use exponential backoff
- Cost: Be aware of AWS costs, especially for compute and storage
Comments (0)
Add a Comment
No comments yet. Be the first to comment!