Cloud7 min read672 lines

Learning state

Track this guide

Saved in this browser only. No account required.

AWS CLI Commands Master Class

Engineering-Grade Reference Manual for AWS CLI
A comprehensive guide to Amazon Web Services command-line interface


Table of Contents

  1. AWS CLI Fundamentals
  2. EC2 (Elastic Compute Cloud)
  3. S3 (Simple Storage Service)
  4. IAM (Identity and Access Management)
  5. VPC (Virtual Private Cloud)
  6. ECS & EKS (Container Services)
  7. Lambda (Serverless)
  8. RDS (Relational Database Service)
  9. CloudFormation
  10. CloudWatch
  11. Route53
  12. Best Practices

AWS CLI Fundamentals

๐Ÿ”น Installation

# macOS
brew install awscli

# Linux
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install

# Verify
aws --version

๐Ÿ”น Configuration

# Configure credentials
aws configure
# AWS Access Key ID: YOUR_ACCESS_KEY
# AWS Secret Access Key: YOUR_SECRET_KEY
# Default region: us-east-1
# Default output format: json

# Multiple profiles
aws configure --profile production
aws configure --profile development

# Use specific profile
aws s3 ls --profile production

# Set default profile
export AWS_PROFILE=production

๐Ÿ”น Output Formats

# JSON (default)
aws ec2 describe-instances

# Table
aws ec2 describe-instances --output table

# Text
aws ec2 describe-instances --output text

# YAML
aws ec2 describe-instances --output yaml

EC2 (Elastic Compute Cloud)

๐Ÿ”น List Instances

# List all instances
aws ec2 describe-instances

# List running instances
aws ec2 describe-instances --filters "Name=instance-state-name,Values=running"

# List with specific tags
aws ec2 describe-instances --filters "Name=tag:Environment,Values=production"

# Get instance IDs only
aws ec2 describe-instances --query 'Reservations[*].Instances[*].InstanceId' --output text

# Formatted output
aws ec2 describe-instances --query 'Reservations[*].Instances[*].[InstanceId,InstanceType,State.Name,PublicIpAddress]' --output table

๐Ÿ”น Launch Instance

# Launch EC2 instance
aws ec2 run-instances \
  --image-id ami-0c55b159cbfafe1f0 \
  --instance-type t2.micro \
  --key-name my-key-pair \
  --security-group-ids sg-0123456789abcdef0 \
  --subnet-id subnet-0123456789abcdef0 \
  --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=MyServer}]'

# Launch with user data
aws ec2 run-instances \
  --image-id ami-0c55b159cbfafe1f0 \
  --instance-type t2.micro \
  --user-data file://user-data.sh \
  --key-name my-key-pair

๐Ÿ”น Manage Instances

# Start instance
aws ec2 start-instances --instance-ids i-1234567890abcdef0

# Stop instance
aws ec2 stop-instances --instance-ids i-1234567890abcdef0

# Reboot instance
aws ec2 reboot-instances --instance-ids i-1234567890abcdef0

# Terminate instance
aws ec2 terminate-instances --instance-ids i-1234567890abcdef0

# Get instance status
aws ec2 describe-instance-status --instance-ids i-1234567890abcdef0

๐Ÿ”น Security Groups

# Create security group
aws ec2 create-security-group \
  --group-name my-sg \
  --description "My security group" \
  --vpc-id vpc-0123456789abcdef0

# Add ingress rule (SSH)
aws ec2 authorize-security-group-ingress \
  --group-id sg-0123456789abcdef0 \
  --protocol tcp \
  --port 22 \
  --cidr 0.0.0.0/0

# Add ingress rule (HTTP)
aws ec2 authorize-security-group-ingress \
  --group-id sg-0123456789abcdef0 \
  --protocol tcp \
  --port 80 \
  --cidr 0.0.0.0/0

# Remove ingress rule
aws ec2 revoke-security-group-ingress \
  --group-id sg-0123456789abcdef0 \
  --protocol tcp \
  --port 22 \
  --cidr 0.0.0.0/0

# List security groups
aws ec2 describe-security-groups

S3 (Simple Storage Service)

๐Ÿ”น Bucket Operations

# List buckets
aws s3 ls

# Create bucket
aws s3 mb s3://my-bucket-name

# Delete bucket
aws s3 rb s3://my-bucket-name

# Delete bucket with contents
aws s3 rb s3://my-bucket-name --force

# List bucket contents
aws s3 ls s3://my-bucket-name

# List recursively
aws s3 ls s3://my-bucket-name --recursive

๐Ÿ”น File Operations

# Upload file
aws s3 cp file.txt s3://my-bucket-name/

# Upload directory
aws s3 cp /local/dir s3://my-bucket-name/dir --recursive

# Download file
aws s3 cp s3://my-bucket-name/file.txt ./

# Download directory
aws s3 cp s3://my-bucket-name/dir /local/dir --recursive

# Sync directory
aws s3 sync /local/dir s3://my-bucket-name/dir

# Move file
aws s3 mv file.txt s3://my-bucket-name/

# Delete file
aws s3 rm s3://my-bucket-name/file.txt

# Delete directory
aws s3 rm s3://my-bucket-name/dir --recursive

๐Ÿ”น Bucket Policies

# Get bucket policy
aws s3api get-bucket-policy --bucket my-bucket-name

# Put bucket policy
aws s3api put-bucket-policy \
  --bucket my-bucket-name \
  --policy file://policy.json

# Delete bucket policy
aws s3api delete-bucket-policy --bucket my-bucket-name

๐Ÿ”น Lifecycle Policies

# Put lifecycle configuration
aws s3api put-bucket-lifecycle-configuration \
  --bucket my-bucket-name \
  --lifecycle-configuration file://lifecycle.json

# Example lifecycle.json
cat > lifecycle.json <<EOF
{
  "Rules": [
    {
      "Id": "DeleteOldFiles",
      "Status": "Enabled",
      "Prefix": "logs/",
      "Expiration": {
        "Days": 30
      }
    },
    {
      "Id": "TransitionToGlacier",
      "Status": "Enabled",
      "Prefix": "archives/",
      "Transitions": [
        {
          "Days": 90,
          "StorageClass": "GLACIER"
        }
      ]
    }
  ]
}
EOF

IAM (Identity and Access Management)

๐Ÿ”น Users

# List users
aws iam list-users

# Create user
aws iam create-user --user-name john

# Delete user
aws iam delete-user --user-name john

# Create access key
aws iam create-access-key --user-name john

# List access keys
aws iam list-access-keys --user-name john

# Delete access key
aws iam delete-access-key --user-name john --access-key-id AKIAIOSFODNN7EXAMPLE

๐Ÿ”น Groups

# List groups
aws iam list-groups

# Create group
aws iam create-group --group-name developers

# Add user to group
aws iam add-user-to-group --user-name john --group-name developers

# Remove user from group
aws iam remove-user-from-group --user-name john --group-name developers

๐Ÿ”น Policies

# List policies
aws iam list-policies

# Create policy
aws iam create-policy \
  --policy-name MyPolicy \
  --policy-document file://policy.json

# Attach policy to user
aws iam attach-user-policy \
  --user-name john \
  --policy-arn arn:aws:iam::123456789012:policy/MyPolicy

# Attach policy to group
aws iam attach-group-policy \
  --group-name developers \
  --policy-arn arn:aws:iam::aws:policy/PowerUserAccess

# List attached policies
aws iam list-attached-user-policies --user-name john

๐Ÿ”น Roles

# List roles
aws iam list-roles

# Create role
aws iam create-role \
  --role-name MyRole \
  --assume-role-policy-document file://trust-policy.json

# Attach policy to role
aws iam attach-role-policy \
  --role-name MyRole \
  --policy-arn arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess

VPC (Virtual Private Cloud)

๐Ÿ”น VPC Operations

# List VPCs
aws ec2 describe-vpcs

# Create VPC
aws ec2 create-vpc --cidr-block 10.0.0.0/16

# Delete VPC
aws ec2 delete-vpc --vpc-id vpc-0123456789abcdef0

# Create subnet
aws ec2 create-subnet \
  --vpc-id vpc-0123456789abcdef0 \
  --cidr-block 10.0.1.0/24 \
  --availability-zone us-east-1a

# List subnets
aws ec2 describe-subnets

# Create internet gateway
aws ec2 create-internet-gateway

# Attach internet gateway
aws ec2 attach-internet-gateway \
  --vpc-id vpc-0123456789abcdef0 \
  --internet-gateway-id igw-0123456789abcdef0

๐Ÿ”น Route Tables

# List route tables
aws ec2 describe-route-tables

# Create route table
aws ec2 create-route-table --vpc-id vpc-0123456789abcdef0

# Create route
aws ec2 create-route \
  --route-table-id rtb-0123456789abcdef0 \
  --destination-cidr-block 0.0.0.0/0 \
  --gateway-id igw-0123456789abcdef0

# Associate route table with subnet
aws ec2 associate-route-table \
  --route-table-id rtb-0123456789abcdef0 \
  --subnet-id subnet-0123456789abcdef0

ECS & EKS (Container Services)

๐Ÿ”น ECS

# List clusters
aws ecs list-clusters

# Create cluster
aws ecs create-cluster --cluster-name my-cluster

# Register task definition
aws ecs register-task-definition --cli-input-json file://task-definition.json

# List task definitions
aws ecs list-task-definitions

# Run task
aws ecs run-task \
  --cluster my-cluster \
  --task-definition my-task:1 \
  --count 1

# List services
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

๐Ÿ”น EKS

# List clusters
aws eks list-clusters

# Create cluster
aws eks create-cluster \
  --name my-cluster \
  --role-arn arn:aws:iam::123456789012:role/eks-service-role \
  --resources-vpc-config subnetIds=subnet-1,subnet-2,securityGroupIds=sg-1

# Get kubeconfig
aws eks update-kubeconfig --name my-cluster

# List node groups
aws eks list-nodegroups --cluster-name my-cluster

# Create node group
aws eks create-nodegroup \
  --cluster-name my-cluster \
  --nodegroup-name my-nodes \
  --subnets subnet-1 subnet-2 \
  --node-role arn:aws:iam::123456789012:role/NodeInstanceRole \
  --scaling-config minSize=1,maxSize=3,desiredSize=2

Lambda (Serverless)

๐Ÿ”น Function Operations

# List functions
aws lambda list-functions

# Create function
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

# Update function code
aws lambda update-function-code \
  --function-name my-function \
  --zip-file fileb://function.zip

# Invoke function
aws lambda invoke \
  --function-name my-function \
  --payload '{"key":"value"}' \
  response.json

# Get function configuration
aws lambda get-function-configuration --function-name my-function

# Delete function
aws lambda delete-function --function-name my-function

RDS (Relational Database Service)

๐Ÿ”น DB Instance Operations

# List 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 postgres \
  --master-username admin \
  --master-user-password mypassword \
  --allocated-storage 20

# Delete DB instance
aws rds delete-db-instance \
  --db-instance-identifier mydb \
  --skip-final-snapshot

# Create snapshot
aws rds create-db-snapshot \
  --db-instance-identifier mydb \
  --db-snapshot-identifier mydb-snapshot

# Restore from snapshot
aws rds restore-db-instance-from-db-snapshot \
  --db-instance-identifier mydb-restored \
  --db-snapshot-identifier mydb-snapshot

CloudFormation

๐Ÿ”น Stack Operations

# List stacks
aws cloudformation list-stacks

# Create stack
aws cloudformation create-stack \
  --stack-name my-stack \
  --template-body file://template.yaml \
  --parameters ParameterKey=KeyName,ParameterValue=my-key

# Update stack
aws cloudformation update-stack \
  --stack-name my-stack \
  --template-body file://template.yaml

# Delete stack
aws cloudformation delete-stack --stack-name my-stack

# Describe stack
aws cloudformation describe-stacks --stack-name my-stack

# Get stack events
aws cloudformation describe-stack-events --stack-name my-stack

CloudWatch

๐Ÿ”น Logs

# List log groups
aws logs describe-log-groups

# Create log group
aws logs create-log-group --log-group-name /aws/lambda/my-function

# Get log events
aws logs filter-log-events \
  --log-group-name /aws/lambda/my-function \
  --start-time 1609459200000

# Tail logs
aws logs tail /aws/lambda/my-function --follow

๐Ÿ”น Metrics

# List metrics
aws cloudwatch list-metrics --namespace AWS/EC2

# 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

Route53

๐Ÿ”น Hosted Zones

# List hosted zones
aws route53 list-hosted-zones

# Create hosted zone
aws route53 create-hosted-zone \
  --name example.com \
  --caller-reference $(date +%s)

# List record sets
aws route53 list-resource-record-sets --hosted-zone-id Z1234567890ABC

Best Practices

โœ… Security

  1. Use IAM roles instead of access keys
  2. Enable MFA for root and IAM users
  3. Use least privilege principle
  4. Rotate credentials regularly
  5. Enable CloudTrail for auditing

โœ… Cost Optimization

  1. Use tags for cost allocation
  2. Set up billing alerts
  3. Use Reserved Instances for predictable workloads
  4. Delete unused resources
  5. Use S3 lifecycle policies

โœ… CLI Usage

  1. Use profiles for multiple accounts
  2. Use --query for filtering output
  3. Use --dry-run to test commands
  4. Script with error handling
  5. Use pagination for large result sets

๐ŸŽ“ AWS CLI Commands Master Class Complete

This guide covers essential AWS CLI commands for managing cloud infrastructure.