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

前端 未结 17 1577
囚心锁ツ
囚心锁ツ 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条回答
  •  萌比男神i
    2021-01-29 23:31

    I created an open-source script that helps you to list all AWS instances. https://github.com/Appnroll/aws-ec2-instances

    That's a part of the script that lists the instances for one profile recording them into an postgreSQL database with using jq for json parsing:

    DATABASE="aws_instances"
    TABLE_NAME="aws_ec2"
    SAVED_FIELDS="state, name, type, instance_id, public_ip, launch_time, region, profile, publicdnsname"
    # collects the regions to display them in the end of script
    REGIONS_WITH_INSTANCES=""
    
    for region in `aws ec2 describe-regions --output text | cut -f3`
    do
       # this mappping depends on describe-instances command output
       INSTANCE_ATTRIBUTES="{
            state: .State.Name,
            name: .KeyName, type: .InstanceType,
            instance_id: .InstanceId,
            public_ip: .NetworkInterfaces[0].Association.PublicIp,
            launch_time: .LaunchTime,
            \"region\": \"$region\",
            \"profile\": \"$AWS_PROFILE\",
            publicdnsname: .PublicDnsName
       }"
    
       echo -e "\nListing AWS EC2 Instances in region:'$region'..."
       JSON=".Reservations[] | ( .Instances[] | $INSTANCE_ATTRIBUTES)"
       INSTANCE_JSON=$(aws ec2 describe-instances --region $region)
    
       if echo $INSTANCE_JSON | jq empty; then
          # "Parsed JSON successfully and got something other than false/null"
          OUT="$(echo $INSTANCE_JSON | jq $JSON)"
    
          # check if empty
          if [[ ! -z "$OUT" ]] then
            for row in $(echo "${OUT}" | jq -c "." ); do
              psql -c "INSERT INTO $TABLE_NAME($SAVED_FIELDS) SELECT $SAVED_FIELDS from json_populate_record(NULL::$TABLE_NAME, '${row}') ON CONFLICT (instance_id)
                DO UPDATE
                SET state = EXCLUDED.state,
                name = EXCLUDED.name,
                type = EXCLUDED.type,
                launch_time = EXCLUDED.launch_time,
                public_ip = EXCLUDED.public_ip,
                profile = EXCLUDED.profile,
                region = EXCLUDED.region,
                publicdnsname = EXCLUDED.publicdnsname
                " -d $DATABASE
            done
    
            REGIONS_WITH_INSTANCES+="\n$region"
          else
            echo "No instances"
          fi
       else
            echo "Failed to parse JSON, or got false/null"
       fi
    done
    

提交回复
热议问题