StackPractices
intermediate By Mathias Paulenko

AWS CLI Bash Scripts

A working set of Bash scripts that wrap the AWS CLI to provision, tag, audit, and clean up AWS resources, including multi-account deploys.

Topics: devops

Overview

Clicking through the AWS Console to spin up a VPC, tag a fleet of instances, or hunt down who left untagged resources running doesn’t scale, and it’s exactly the kind of work that drifts out of sync between environments. These Bash scripts wrap the AWS CLI — Amazon’s official command-line tool for scripting against its APIs — so provisioning, tagging, auditing, and cleanup are one command away instead of a dozen console clicks.

Each script is self-contained: adjust the variables at the top, run it, done. They all assume AWS CLI v2 configured (aws configure, environment variables, or SSO) and set -euo pipefail so a failed API call stops the script instead of half-applying changes. If you’re new to shell scripting for ops work, Bash Scripting for DevOps Automation covers the fundamentals first.

When to Use

  • You need to provision or tear down AWS resources repeatedly: test stacks, sandboxes, demo environments.
  • You want consistent tagging across EC2, S3, and VPC resources; pair this with a written policy like the Cloud Resource Tagging Policy template.
  • You’re auditing IAM users, access keys, or required-tag coverage across an account.
  • You’re automating cleanup of dev environments to keep the bill down; combine with the Complete Guide to AWS Cost Optimization for the bigger picture.
  • You deploy the same workload to several AWS accounts from one pipeline or workstation.
  • This is not the right tool for long-lived production infrastructure. For that you want Terraform, CloudFormation, or CDK. They track state and detect drift, which a shell script can’t.

Solution

Provision an EC2 instance

The classic case: launch an instance and wait until it’s actually running before printing its public IP. aws ec2 wait blocks until the state changes, which beats polling with sleep.

#!/bin/bash

set -euo pipefail

INSTANCE_NAME="web-server-01"
AMI_ID="ami-0c55b159cbfafe1f0"  # example ID — pick a current AMI for your region
INSTANCE_TYPE="t3.micro"
KEY_NAME="my-key-pair"         # your key pair name
SECURITY_GROUP="sg-12345678"   # your security group ID
SUBNET_ID="subnet-12345678"    # your subnet ID

INSTANCE_ID=$(aws ec2 run-instances \
    --image-id "$AMI_ID" \
    --instance-type "$INSTANCE_TYPE" \
    --key-name "$KEY_NAME" \
    --security-group-ids "$SECURITY_GROUP" \
    --subnet-id "$SUBNET_ID" \
    --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=${INSTANCE_NAME}}]" \
    --query 'Instances[0].InstanceId' \
    --output text)

echo "Launched instance: $INSTANCE_ID"

# Wait for instance to be running
aws ec2 wait instance-running --instance-ids "$INSTANCE_ID"

# Get public IP
PUBLIC_IP=$(aws ec2 describe-instances \
    --instance-ids "$INSTANCE_ID" \
    --query 'Reservations[0].Instances[0].PublicIpAddress' \
    --output text)

echo "Instance running at: $PUBLIC_IP"

List all EC2 instances with details

A one-liner that produces a report-style table, handy for a quick account overview or a daily cron digest.

#!/bin/bash

set -euo pipefail

aws ec2 describe-instances \
    --query 'Reservations[*].Instances[*].[InstanceId,State.Name,InstanceType,PublicIpAddress,Tags[?Key==`Name`].Value | [0]]' \
    --output table

Create an ephemeral test VPC with auto-cleanup

For test stacks you want resources tagged and gone when you’re done. The EXIT trap deletes the subnet and VPC automatically; export KEEP=1 to keep them instead. Without the trap a failed script leaves a half-built network billing you by the hour.

#!/usr/bin/env bash
set -euo pipefail

REGION="${AWS_REGION:-us-east-1}"
PROJECT="${1:-demo}"
ENV="${2:-dev}"

TAGS="Key=Project,Value=$PROJECT Key=Environment,Value=$ENV Key=ManagedBy,Value=bash-script"

# Create a VPC with tags
VPC_ID=$(aws ec2 create-vpc --cidr-block 10.0.0.0/16 --region "$REGION" --query 'Vpc.VpcId' --output text)
aws ec2 create-tags --resources "$VPC_ID" --tags $TAGS --region "$REGION"

SUBNET_ID=""

# Cleanup function: deletes in dependency order (subnet before VPC)
cleanup() {
    echo "Tearing down ${SUBNET_ID:-none} and $VPC_ID"
    if [ -n "$SUBNET_ID" ]; then
        aws ec2 delete-subnet --subnet-id "$SUBNET_ID" --region "$REGION" || true
    fi
    aws ec2 delete-vpc --vpc-id "$VPC_ID" --region "$REGION" || true
}

# Register the teardown right away, before anything else can fail —
# unless KEEP=1 is exported
if [ "${KEEP:-0}" != "1" ]; then
    trap cleanup EXIT
fi

# Create a subnet
SUBNET_ID=$(aws ec2 create-subnet --vpc-id "$VPC_ID" --cidr-block 10.0.1.0/24 --region "$REGION" --query 'Subnet.SubnetId' --output text)
aws ec2 create-tags --resources "$SUBNET_ID" --tags $TAGS --region "$REGION"

echo "Created VPC $VPC_ID and subnet $SUBNET_ID"

The || true in cleanup matters: if the subnet is already gone, the teardown failure won’t mask the script’s real exit status.

Create and configure an S3 bucket

Bucket creation has one real gotcha: us-east-1 must not get a LocationConstraint, every other region must. This script also turns on versioning and applies a lifecycle policy that moves objects through storage tiers before expiring them.

#!/bin/bash

set -euo pipefail

BUCKET_NAME="my-app-backups-$(date +%Y%m%d)"
REGION="us-east-1"

# Create bucket: us-east-1 takes no LocationConstraint
if [ "$REGION" = "us-east-1" ]; then
    aws s3api create-bucket --bucket "$BUCKET_NAME"
else
    aws s3api create-bucket \
        --bucket "$BUCKET_NAME" \
        --region "$REGION" \
        --create-bucket-configuration LocationConstraint="$REGION"
fi

echo "Created bucket: $BUCKET_NAME"

# Enable versioning
aws s3api put-bucket-versioning \
    --bucket "$BUCKET_NAME" \
    --versioning-configuration Status=Enabled

# Lifecycle: logs move to Infrequent Access at 30 days, Glacier at 90, expire at 365
cat > /tmp/lifecycle.json << 'EOF'
{
    "Rules": [
        {
            "ID": "LogLifecycleRule",
            "Status": "Enabled",
            "Filter": { "Prefix": "logs/" },
            "Transitions": [
                { "Days": 30, "StorageClass": "STANDARD_IA" },
                { "Days": 90, "StorageClass": "GLACIER" }
            ],
            "Expiration": { "Days": 365 },
            "NoncurrentVersionExpiration": { "NoncurrentDays": 30 }
        }
    ]
}
EOF

aws s3api put-bucket-lifecycle-configuration \
    --bucket "$BUCKET_NAME" \
    --lifecycle-configuration file:///tmp/lifecycle.json

echo "Versioning and lifecycle policy configured"

# Audit: list objects under the prefix older than 90 days
# date -d is GNU date — on macOS install coreutils and use gdate
aws s3api list-objects-v2 \
    --bucket "$BUCKET_NAME" \
    --prefix "logs/" \
    --query "Contents[?LastModified<='$(date -d '90 days ago' -I)'].[Key,LastModified,Size]" \
    --output table

Sync a local directory to S3

aws s3 sync is the workhorse for backups and static asset uploads. --delete mirrors deletions too, so treat the destination as authoritative.

#!/bin/bash

set -euo pipefail

LOCAL_DIR="/var/backups/app"
S3_BUCKET="my-app-backups"
S3_PREFIX="daily"

# Sync with delete and exclude temp files
aws s3 sync "$LOCAL_DIR" "s3://${S3_BUCKET}/${S3_PREFIX}/" \
    --delete \
    --exclude "*.tmp" \
    --exclude "*.lock" \
    --storage-class STANDARD_IA

echo "Synced $LOCAL_DIR to s3://${S3_BUCKET}/${S3_PREFIX}/"

Stop EC2 instances by tag

This one is the classic Friday-evening cost saver: it shuts down everything tagged Environment=dev. The reverse works the same way — swap stop-instances/instance-stopped for start-instances/instance-running.

#!/bin/bash

set -euo pipefail

# Stop all instances tagged Environment=dev
INSTANCE_IDS=$(aws ec2 describe-instances \
    --filters "Name=tag:Environment,Values=dev" "Name=instance-state-name,Values=running" \
    --query 'Reservations[*].Instances[*].InstanceId' \
    --output text)

if [ -z "$INSTANCE_IDS" ]; then
    echo "No running dev instances found"
    exit 0
fi

echo "Stopping instances: $INSTANCE_IDS"
aws ec2 stop-instances --instance-ids $INSTANCE_IDS

# Wait for stop
aws ec2 wait instance-stopped --instance-ids $INSTANCE_IDS
echo "All dev instances stopped"

IAM user audit

Run this before the next security review does it for you: the script dumps each IAM user’s access keys, attached policies, and group membership, which is the quick way to surface stale keys and over-privileged accounts.

#!/bin/bash

set -euo pipefail

echo "=== IAM User Audit ==="
echo "Date: $(date)"
echo ""

# List all users
USERS=$(aws iam list-users --query 'Users[*].UserName' --output text)

for user in $USERS; do
    echo "--- User: $user ---"

    # Get access keys (tolerate per-user permission failures)
    KEYS=$(aws iam list-access-keys --user-name "$user" --output text 2>/dev/null || echo "")
    if [ -n "$KEYS" ]; then
        echo "Access keys:"
        echo "$KEYS" | tr '\t' '\n'
    else
        echo "No access keys"
    fi

    # Get attached policies
    POLICIES=$(aws iam list-attached-user-policies --user-name "$user" \
        --query 'AttachedPolicies[*].PolicyName' --output text 2>/dev/null || echo "")
    if [ -n "$POLICIES" ]; then
        echo "Attached policies: $POLICIES"
    fi

    # Get groups
    GROUPS=$(aws iam list-groups-for-user --user-name "$user" \
        --query 'Groups[*].GroupName' --output text 2>/dev/null || echo "")
    if [ -n "$GROUPS" ]; then
        echo "Groups: $GROUPS"
    fi

    echo ""
done

Backup RDS snapshot

Creates a snapshot, waits for it to finish, then prunes anything older than your retention window. Run it nightly from cron or a CI schedule.

#!/bin/bash

set -euo pipefail

DB_INSTANCE="my-database"
SNAPSHOT_ID="${DB_INSTANCE}-snapshot-$(date +%Y%m%d-%H%M%S)"

aws rds create-db-snapshot \
    --db-instance-identifier "$DB_INSTANCE" \
    --db-snapshot-identifier "$SNAPSHOT_ID"

echo "Creating snapshot: $SNAPSHOT_ID"

# Wait for snapshot to complete
aws rds wait db-snapshot-available \
    --db-snapshot-identifier "$SNAPSHOT_ID"

echo "Snapshot created: $SNAPSHOT_ID"

# Clean up manual snapshots older than 30 days
# --snapshot-type manual skips automated backups, which delete-db-snapshot can't remove
OLD_SNAPSHOTS=$(aws rds describe-db-snapshots \
    --db-instance-identifier "$DB_INSTANCE" \
    --snapshot-type manual \
    --query "DBSnapshots[?SnapshotCreateTime<\`$(date -d '30 days ago' -I)\`].DBSnapshotIdentifier" \
    --output text)

for snapshot in $OLD_SNAPSHOTS; do
    echo "Deleting old snapshot: $snapshot"
    aws rds delete-db-snapshot --db-snapshot-identifier "$snapshot"
done

More Scripts: Auditing, Cleanup, and Deployment

The next batch covers the operational side: enforcing tag policy, rotating backups, publishing dashboards, and pushing the same artifact to your dev, staging, and prod accounts.

Audit required tags across EC2 and S3

This is the script that pays for itself during a cost-allocation review: it reports every running instance and every bucket missing a required tag. It needs jq for the nested tag arrays: brew install jq or apt install jq.

#!/usr/bin/env bash
set -euo pipefail

REGION="${AWS_REGION:-us-east-1}"
REQUIRED_TAGS=("Project" "Environment" "Owner" "CostCenter")

# Audit EC2 instances for missing required tags
INSTANCES=$(aws ec2 describe-instances \
    --query 'Reservations[*].Instances[?State.Name==`running`].[InstanceId,Tags]' \
    --output json \
    --region "$REGION")

echo "$INSTANCES" | jq -c '.[]' | while read -r instance; do
    instance_id=$(echo "$instance" | jq -r '.[0]')
    tags=$(echo "$instance" | jq -r '.[1] // [] | map(.Key)')
    missing=()
    for req_tag in "${REQUIRED_TAGS[@]}"; do
        if ! echo "$tags" | grep -q "\"$req_tag\""; then
            missing+=("$req_tag")
        fi
    done
    if [ ${#missing[@]} -gt 0 ]; then
        echo "VIOLATION: $instance_id missing tags: ${missing[*]}"
    fi
done

# Audit S3 buckets for missing tags
# Buckets can live in other regions — resolve each one's location first,
# otherwise get-bucket-tagging fails with PermanentRedirect and reports false positives
BUCKETS=$(aws s3api list-buckets --query 'Buckets[*].Name' --output text --region "$REGION")
for bucket in $BUCKETS; do
    BUCKET_REGION=$(aws s3api get-bucket-location --bucket "$bucket" \
        --query 'LocationConstraint' --output text 2>/dev/null || echo "")
    [ "$BUCKET_REGION" = "None" ] && BUCKET_REGION="us-east-1"
    bucket_tags=$(aws s3api get-bucket-tagging --bucket "$bucket" \
        --region "${BUCKET_REGION:-$REGION}" \
        --query 'TagSet[*].Key' --output text 2>/dev/null || echo "")
    missing=()
    for req_tag in "${REQUIRED_TAGS[@]}"; do
        if ! echo "$bucket_tags" | grep -qw "$req_tag"; then
            missing+=("$req_tag")
        fi
    done
    if [ ${#missing[@]} -gt 0 ]; then
        echo "VIOLATION: bucket $bucket missing tags: ${missing[*]}"
    fi
done

The audit above only looks at EC2 and S3; for the same check across RDS, Lambda, and the rest of your account, reach for aws resourcegroupstaggingapi get-resources — the FAQ shows how to filter it down to untagged ARNs.

Rotate EBS snapshots with retention

Snapshots every volume tagged Backup=true, tags each snapshot with its creation date, then deletes the ones past retention. Scheduled daily, it gives you a self-cleaning backup chain.

#!/usr/bin/env bash
set -euo pipefail

REGION="${AWS_REGION:-us-east-1}"
RETENTION_DAYS="${1:-30}"

# Create snapshots of all EBS volumes with the Backup tag
VOLUME_IDS=$(aws ec2 describe-volumes \
    --filters "Name=tag:Backup,Values=true" \
    --query 'Volumes[*].VolumeId' \
    --output text \
    --region "$REGION")

for vol_id in $VOLUME_IDS; do
    SNAP_ID=$(aws ec2 create-snapshot \
        --volume-id "$vol_id" \
        --description "Automated backup $(date -I)" \
        --tag-specifications "ResourceType=snapshot,Tags=[{Key=CreatedBy,Value=bash-script},{Key=Date,Value=$(date -I)}]" \
        --query 'SnapshotId' \
        --output text \
        --region "$REGION")
    echo "Created snapshot $SNAP_ID for volume $vol_id"
done

# Delete snapshots older than retention period
CUTOFF=$(date -d "$RETENTION_DAYS days ago" -I)
OLD_SNAPS=$(aws ec2 describe-snapshots \
    --owner-ids self \
    --filters "Name=tag:CreatedBy,Values=bash-script" \
    --query "Snapshots[?StartTime<='$CUTOFF'].SnapshotId" \
    --output text \
    --region "$REGION")

for snap_id in $OLD_SNAPS; do
    aws ec2 delete-snapshot --snapshot-id "$snap_id" --region "$REGION"
    echo "Deleted old snapshot $snap_id"
done

Clean up unattached EBS volumes

Detached volumes keep billing you long after the instance they served is gone. This finds every available volume and deletes it. Run a dry pass first by commenting out the delete-volume call.

#!/bin/bash

set -euo pipefail

# Find unattached volumes
VOLUMES=$(aws ec2 describe-volumes \
    --filters "Name=status,Values=available" \
    --query 'Volumes[*].[VolumeId,Size,Tags[?Key==`Name`].Value | [0]]' \
    --output text)

if [ -z "$VOLUMES" ]; then
    echo "No unused volumes found"
    exit 0
fi

echo "Unused EBS volumes:"
echo "$VOLUMES"

# Delete each volume
for vol_id in $(echo "$VOLUMES" | awk '{print $1}'); do
    echo "Deleting volume: $vol_id"
    aws ec2 delete-volume --volume-id "$vol_id"
done

echo "Cleanup complete"

Monitor costs with AWS Cost Explorer

The Cost Explorer API reports daily spend per service; this prints the last 30 days, ready to pipe into a file or a Slack webhook for a morning cost report.

#!/bin/bash

set -euo pipefail

START_DATE=$(date -d "30 days ago" +%Y-%m-%d)
END_DATE=$(date +%Y-%m-%d)

aws ce get-cost-and-usage \
    --time-period Start="$START_DATE",End="$END_DATE" \
    --granularity DAILY \
    --metrics UnblendedCost \
    --group-by Type=DIMENSION,Key=SERVICE \
    --query 'ResultsByTime[*].[TimePeriod.Start,Groups[*].[Keys[0],Metrics.UnblendedCost.Amount]]' \
    --output table

Publish a CloudWatch dashboard

Dashboards are just JSON documents. Keeping one in a script means every environment gets the same panels instead of a hand-assembled console view.

#!/usr/bin/env bash
set -euo pipefail

REGION="${AWS_REGION:-us-east-1}"
DASHBOARD_NAME="${1:-app-overview}"

DASHBOARD_BODY=$(cat <<EOF
{
    "widgets": [
        {
            "type": "metric",
            "x": 0, "y": 0, "width": 12, "height": 6,
            "properties": {
                "metrics": [
                    ["AWS/EC2", "CPUUtilization", "AutoScalingGroupName", "app-asg"],
                    [".", "NetworkIn", ".", "."]
                ],
                "period": 300,
                "stat": "Average",
                "region": "$REGION",
                "title": "EC2 CPU and Network"
            }
        },
        {
            "type": "metric",
            "x": 12, "y": 0, "width": 12, "height": 6,
            "properties": {
                "metrics": [
                    ["AWS/RDS", "CPUUtilization", "DBInstanceIdentifier", "app-db"],
                    [".", "DatabaseConnections", ".", "."]
                ],
                "period": 300,
                "stat": "Average",
                "region": "$REGION",
                "title": "RDS CPU and Connections"
            }
        },
        {
            "type": "log",
            "x": 0, "y": 6, "width": 24, "height": 6,
            "properties": {
                "query": "SOURCE 'app-logs' | fields @timestamp, level, message | filter level = \"ERROR\" | sort @timestamp desc | limit 20",
                "region": "$REGION",
                "title": "Recent Errors"
            }
        }
    ]
}
EOF
)

aws cloudwatch put-dashboard \
    --dashboard-name "$DASHBOARD_NAME" \
    --dashboard-body "$DASHBOARD_BODY" \
    --region "$REGION"

echo "Dashboard $DASHBOARD_NAME created"

Note the unquoted EOF: the heredoc expands $REGION into the JSON. Use <<'EOF' if you don’t want expansion.

Deploy to multiple AWS accounts with assume-role

For an artifact that ships to dev, staging, and prod accounts, loop over assume-role, export the temporary credentials, deploy, and clear them before the next account. Never keep long-lived keys for this.

#!/usr/bin/env bash
set -euo pipefail

REGION="${AWS_REGION:-us-east-1}"
ACCOUNTS=("dev:111111111111" "staging:222222222222" "prod:333333333333")  # replace with your account IDs
ROLE_NAME="DeploymentRole"

for account in "${ACCOUNTS[@]}"; do
    ENV="${account%%:*}"
    ACCOUNT_ID="${account##*:}"

    echo "=== Deploying to $ENV ($ACCOUNT_ID) ==="

    # Assume the deployment role in this account
    CREDS=$(aws sts assume-role \
        --role-arn "arn:aws:iam::$ACCOUNT_ID:role/$ROLE_NAME" \
        --role-session-name "deploy-$ENV-$(date +%s)" \
        --query 'Credentials' \
        --output json)

    export AWS_ACCESS_KEY_ID=$(echo "$CREDS" | jq -r '.AccessKeyId')
    export AWS_SECRET_ACCESS_KEY=$(echo "$CREDS" | jq -r '.SecretAccessKey')
    export AWS_SESSION_TOKEN=$(echo "$CREDS" | jq -r '.SessionToken')

    # Deploy: update Lambda function
    aws lambda update-function-code \
        --function-name "app-handler" \
        --zip-file "fileb://dist/handler.zip" \
        --region "$REGION"

    # Verify deployment
    STATUS=$(aws lambda get-function \
        --function-name "app-handler" \
        --query 'Configuration.LastUpdateStatus' \
        --output text)

    echo "Deployment to $ENV: $STATUS"

    # Clear credentials before the next account
    unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN
done
Multi-account deploy loop: for each account, assume-role, export temporary credentials, update Lambda code, verify status, clear credentials, move to the next account

Companion files: all of these scripts are collected in the bash-aws-cli-scripts companion repo, one .sh file each, ready to copy and run.

Explanation

By default the CLI answers with JSON, which is awkward to parse in bash. --query takes a JMESPath expression that filters and shapes the response client-side, after the full response arrives — don’t confuse it with --filters, which some APIs accept to filter server-side before anything comes back. --output text gives you one plain value per line, perfect for $(...) capture, while --output table prints something a human can actually read. When the filter gets more complex than JMESPath comfortably handles, switch to --output json and pipe through jq, like the tag audit does.

Worth knowing before you schedule these:

  • Exit codes: 0 success, 252 for invalid syntax or parameters, 253 for config or credential problems, 254 when the request reached the service but the service returned an error, 255 as a general catch-all. With set -e, any non-zero stops the script. Wrap optional calls in if ! aws ...; then or append || true.
  • --dry-run works on most mutating EC2 calls: AWS checks permissions and parameters and touches nothing. Run any destructive script this way the first time.
  • wait commands: they poll until a resource reaches a state (running, stopped, snapshot-available). More reliable than fixed sleep delays.
  • date -d is GNU-specific: it fails on macOS, where the equivalent is date -v-30d. Install coreutils (gdate) or branch on uname.
  • trap ... EXIT: the safest way to guarantee teardown, but make it opt-out (the KEEP=1 pattern above) so nobody provisions a stack and watches it delete itself.

Variants

ApproachToolComplexityUse When
AWS CLI + bashaws cliLowQuick scripts, scheduled ops tasks
AWS SDK (Python)boto3MediumComplex logic, richer error handling
AWS SDK (JavaScript)aws-sdkMediumNode.js environments
TerraformterraformHighDeclarative infrastructure as code
CloudFormationaws cloudformationHighNative AWS IaC, stack lifecycle

Bash + AWS CLI wins when the task is operational (sync, audit, rotate, clean up) and loses when the task is declarative infrastructure that needs state. The moment you find yourself tracking “what did I create last run” in a text file, it’s time for Terraform.

What Works

  • Always set set -euo pipefail at the top of scripts. Fail fast on errors.
  • Use --query to extract only the fields you need; reach for jq only when the filtering gets nested.
  • Every aws <service> wait call polls AWS for you and returns the moment the resource is ready, so you never have to guess how long to sleep.
  • Tag everything at creation time; the compliance audit above shows why retrofitting tags is painful.
  • Test mutating calls with --dry-run (or a commented-out delete) before letting a script touch real resources.
  • Assume least-privilege roles via aws sts assume-role instead of embedding long-lived access keys.
  • Run mutating scripts against a sandbox account first — a dedicated --profile or a test OU in AWS Organizations keeps a bad run away from prod.

Common Mistakes

  • Embedding AWS credentials in scripts. Use environment variables, IAM roles, or SSO instead.
  • Not handling API rate limits. AWS throttles requests; the CLI already retries automatically in its default standard mode, but you can raise the ceiling with AWS_MAX_ATTEMPTS or switch retry_mode in ~/.aws/config — and space out calls in tight loops.
  • Forgetting to wait for async operations, and the script continues before the resource is ready.
  • Deleting a VPC before its subnets and dependencies. Teardown has to run in dependency order.
  • Relying on the default region silently. Always set AWS_REGION or pass --region explicitly.
  • Registering the cleanup trap too late. If the script dies between creating a resource and registering its EXIT trap, the resource orphans — set the trap right after the first creation call, like the ephemeral VPC script does.

See Also

Frequently Asked Questions

How do I handle AWS CLI errors in bash?

Check the exit code and capture stderr:

if ! aws s3 ls "s3://my-bucket" 2>/dev/null; then
    echo "Bucket does not exist or access denied"
    exit 1
fi

The CLI returns 0 on success, 252 for syntax or parameter problems, 253 for config or credential problems, 254 for service-side errors, and 255 as a general catch-all.

Can I run commands under an assumed IAM role?
ROLE_ARN="arn:aws:iam::123456789012:role/MyRole"

CREDENTIALS=$(aws sts assume-role \
    --role-arn "$ROLE_ARN" \
    --role-session-name "my-script" \
    --query 'Credentials' \
    --output json)

export AWS_ACCESS_KEY_ID=$(echo "$CREDENTIALS" | jq -r '.AccessKeyId')
export AWS_SECRET_ACCESS_KEY=$(echo "$CREDENTIALS" | jq -r '.SecretAccessKey')
export AWS_SESSION_TOKEN=$(echo "$CREDENTIALS" | jq -r '.SessionToken')

# Now run AWS commands as the assumed role
aws s3 ls
How do I run the same command across multiple regions?
REGIONS=("us-east-1" "us-west-2" "eu-west-1")

for region in "${REGIONS[@]}"; do
    echo "=== Region: $region ==="
    aws ec2 describe-instances --region "$region" \
        --query 'Reservations[*].Instances[*].[InstanceId,State.Name]' \
        --output table
done

If you don't want to hardcode the list, aws ec2 describe-regions --query 'Regions[].RegionName' --output text hands you every region your account can see.

Can I test destructive operations without applying them?

Use --dry-run. AWS validates the request without making changes:

aws ec2 terminate-instances --instance-ids "i-12345678" --dry-run

A DryRunOperation error means the request would have worked; UnauthorizedOperation means your credentials can't.

What covers untagged resources beyond EC2 and S3?

The Resource Groups Tagging API covers most AWS services in one call. This JMESPath filter returns only the ARNs that carry no tags at all:

aws resourcegroupstaggingapi get-resources \
    --query 'ResourceTagMappingList[?Tags==`[]`].ResourceARN' \
    --output text

From there you pipe each ARN to the matching service's delete command. There's no universal delete API, so it's aws ec2 delete-snapshot for snapshots, aws s3 rb for buckets, and so on down the line.