How to see all running Amazon EC2 instances across all regions?

前端 未结 17 1279
囚心锁ツ
囚心锁ツ 2021-01-29 23:03

I switch instances between different regions frequently and sometimes I forget to turn off my running instance from a different region. I couldn\'t find any way to see all the r

17条回答
  •  悲&欢浪女
    2021-01-29 23:24

    My script below, based on various tips from this post and elsewhere. The script is easier to follow (for me at least) than the long command lines.

    The script assumes credential profile(s) are stored in file ~/.aws/credentials looking something like:

    [default]
    aws_access_key_id = foobar
    aws_secret_access_key = foobar
    
    [work]
    aws_access_key_id = foobar
    aws_secret_access_key = foobar
    

    Script:

    #!/usr/bin/env bash
    
    #------------------------------------#
    # Script to display AWS EC2 machines #
    #------------------------------------#
    
    # NOTES:
    # o Requires 'awscli' tools (for ex. on MacOS: $ brew install awscli)
    # o AWS output is tabbed - we convert to spaces via 'column' command
    
    
    #~~~~~~~~~~~~~~~~~~~~#
    # Assemble variables #
    #~~~~~~~~~~~~~~~~~~~~#
    
    regions=$(aws ec2 describe-regions --output text | cut -f4 | sort)
    
    query_mach='Reservations[].Instances[]'
    query_flds='PrivateIpAddress,InstanceId,InstanceType'
    query_tags='Tags[?Key==`Name`].Value[]'
    query_full="$query_mach.[$query_flds,$query_tags]"
    
    
    #~~~~~~~~~~~~~~~~~~~~~~~~#
    # Output AWS information #
    #~~~~~~~~~~~~~~~~~~~~~~~~#
    
    # Iterate through credentials profiles
    for profile in 'default' 'work'; do
    
        # Print profile header
        echo -e "\n"
        echo -e "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
        echo -e "Credentials profile:'$profile'..."
        echo -e "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    
        # Iterate through all regions
        for region in $regions; do
    
            # Print region header
            echo -e "\n"
            echo -e "Region: $region..."
            echo -e "--------------------------------------------------------------"
    
            # Output items for the region
            aws ec2 describe-instances    \
              --profile $profile          \
              --region  $region           \
              --query   $query_full       \
              --output  text              \
              | sed     's/None$/None\n/' \
              | sed     '$!N;s/\n/ /'     \
              | column  -t -s $'\t'
    
        done
    done
    

提交回复
热议问题