简体   繁体   English

如何查看所有区域中所有正在运行的 Amazon EC2 实例?

[英]How to see all running Amazon EC2 instances across all regions?

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 running instances on Amazon console.我找不到任何方法来查看亚马逊控制台上所有正在运行的实例。
Is there any way to display all the running instances regardless of region?有什么方法可以显示所有正在运行的实例而不考虑区域?

Nov 2021 Edit : AWS has recently launched the Amazon EC2 Global View with initial support for Instances, VPCs, Subnets, Security Groups and Volumes. 2021 年 11 月编辑:AWS 最近推出了Amazon EC2 全局视图,初步支持实例、VPC、子网、安全组和卷。

See the announcement or documentation for more details有关详细信息,请参阅公告文档


A non-obvious GUI option is the Tag Editor in the Resource Groups console.一个不明显的 GUI 选项是资源组控制台中的标记编辑器 Here you can find all instances across all regions, even if the instances were not tagged.在这里,您可以找到所有区域的所有实例,即使这些实例没有被标记。 的屏幕截图

I don't think you can currently do this in the AWS GUI.我认为您目前无法在 AWS GUI 中执行此操作。 But here is a way to list all your instances across all regions with the AWS CLI:但这是一种使用 AWS CLI 列出所有区域中所有实例的方法:

for region in `aws ec2 describe-regions --region us-east-1 --output text | cut -f4`
do
     echo -e "\nListing Instances in region:'$region'..."
     aws ec2 describe-instances --region $region
done

Taken from here (If you want to see full discussion)取自这里(如果你想看到完整的讨论)

Also, if you're getting a另外,如果你得到一个

You must specify a region.您必须指定一个区域。 You can also configure your region by running "aws configure"您还可以通过运行“aws configure”来配置您的区域

You can do so with aws configure set region us-east-1 , thanks @Sabuncu for the comment.您可以使用aws configure set region us-east-1执行此操作,感谢@Sabuncu 的评论。

Update更新

Now (in 2019) the cut command should be applied on the 4th field: cut -f4现在(在 2019 年)应该在第 4 个字段上应用 cut 命令: cut -f4

In Console在控制台中

Go to VPC dashboard https://console.aws.amazon.com/vpc/home and click on Running instances -> See all regions .转到 VPC 仪表板https://console.aws.amazon.com/vpc/home并单击Running instances -> See all regions

在此处输入图像描述

In CLI在 CLI 中

Add this for example to .bashrc .例如,将此添加到.bashrc Reload it source ~/.bashrc , and run it重新加载它source ~/.bashrc ,然后运行它

Note: Except for aws CLI you need to have jq installed注意:除了aws CLI ,您需要安装jq

function aws.print-all-instances() {
  REGIONS=`aws ec2 describe-regions --region us-east-1 --output text --query Regions[*].[RegionName]`
  for REGION in $REGIONS
  do
    echo -e "\nInstances in '$REGION'..";
    aws ec2 describe-instances --region $REGION | \
      jq '.Reservations[].Instances[] | "EC2: \(.InstanceId): \(.State.Name)"'
  done
}

Example output:示例输出:

$ aws.print-all-instances 

Listing Instances in region: 'eu-north-1'..
"EC2: i-0548d1de00c39f923: terminated"
"EC2: i-0fadd093234a1c21d: running"

Listing Instances in region: 'ap-south-1'..

Listing Instances in region: 'eu-west-3'..

Listing Instances in region: 'eu-west-2'..

Listing Instances in region: 'eu-west-1'..

Listing Instances in region: 'ap-northeast-2'..

Listing Instances in region: 'ap-northeast-1'..

Listing Instances in region: 'sa-east-1'..

Listing Instances in region: 'ca-central-1'..

Listing Instances in region: 'ap-southeast-1'..

Listing Instances in region: 'ap-southeast-2'..

Listing Instances in region: 'eu-central-1'..

Listing Instances in region: 'us-east-1'..

Listing Instances in region: 'us-east-2'..

Listing Instances in region: 'us-west-1'..

Listing Instances in region: 'us-west-2'..
  1. First go to AWS Management console and click on Resource group:首先转到AWS 管理控制台并单击资源组:

    在此处输入图像描述

  2. Then find Network and Content Delivery and click on the VPC :然后找到Network and Content Delivery并点击VPC

    在此处输入图像描述

  3. Then find Running instances and expand see all regions.然后找到正在运行的实例并展开查看所有区域。 Here you can find all the running instances of all region:在这里您可以找到所有区域的所有正在运行的实例:

    在此处输入图像描述

@imTachu solution works well. @imTachu 解决方案效果很好。 To do this via the AWS console...要通过 AWS 控制台执行此操作...

  • AWS console AWS 控制台
  • Services服务
  • Networking & Content Delivery网络和内容交付
  • VPC专有网络
  • Look for a block named "Running Instances", this will show you the current region查找名为“Running Instances”的块,这将显示当前区域
  • Click the "See all regions" link underneath点击下方的“查看所有地区”链接

每次创建资源时,使用名称标记它,现在您可以使用资源组在所有区域中查找具有名称标记的所有类型的资源。

After reading through all the solutions and trying bunch of stuff, the one that worked for me was-在阅读了所有解决方案并尝试了一堆东西之后,对我有用的是 -

  1. List item项目清单
  2. Go to Resource Group转到资源组
  3. Tag Editor标签编辑器
  4. Select All Regions选择所有地区
  5. Select EC2 Instance in resource type在资源类型中选择 EC2 实例
  6. Click Search Resources点击搜索资源

解决方案快照

Based on imTachus answer but less verbose, plus faster.基于 imTachus 的回答,但不那么冗长,而且速度更快。 You need to have jq and aws-cli installed.您需要安装jqaws-cli

set +m
for region in $(aws ec2 describe-regions --query "Regions[*].[RegionName]" --output text); do 
  aws ec2 describe-instances --region "$region" | jq ".Reservations[].Instances[] | {type: .InstanceType, state: .State.Name, tags: .Tags, zone: .Placement.AvailabilityZone}" &
done; wait; set -m

The script runs the aws ec2 describe-instances in parallel for each region (now 15!) and extracts only the relevant bits (state, tags, availability zone) from the json output.该脚本为每个区域(现在是 15 个!)并行运行aws ec2 describe-instances ,并从 json 输出中仅提取相关位(状态、标签、可用区)。 The set +m is needed so the background processes don't report when starting/ending. set +m是必需的,因此后台进程在启动/结束时不会报告。

Example output:示例输出:

{
  "type": "t2.micro",
  "state": "stopped",
  "tags": [
    {
      "Key": "Name",
      "Value": "MyEc2WebServer"
    },
  ],
  "zone": "eu-central-1b"
}

You can run DescribeInstances() across all regions.您可以跨所有区域运行DescribeInstances()

Additionally, you can:此外,您还可以:

  • Automate it through Lambda and Cloud watch.通过 Lambda 和 Cloud watch 实现自动化。
  • Create api endpoint using Lambda and api gateway and use it in your code使用 Lambda 和 api 网关创建 api 端点并在您的代码中使用它

A sample in NodeJS: NodeJS 中的一个示例:

var regionNames = ['us-west-1', 'us-west-2', 'us-east-1', 'eu-west-1', 'eu-central-1', 'sa-east-1', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ap-northeast-2'];

    regionNames.forEach(function(region) {
        getInstances(region);
    });
  • Then, in getInstances function, DescribeInstances() can be called.然后,在getInstances函数中,可以调用DescribeInstances()
function getInstances(region) {
            EC2.describeInstances(params, function(err, data) {
                if (err) return console.log("Error connecting to AWS, No Such Instance Found!");
                data.Reservations.forEach(function(reservation) {
                //do any operation intended
      });
    }

And Off Course, feel free to use ES6 and above.当然,请随意使用 ES6 及更高版本。

I wrote a lambda function to get you all the instances in any state [running, stopped] and from any regions, will also give details about instance type and various other parameters.我编写了一个 lambda 函数来获取处于任何状态 [运行、停止] 和来自任何区域的所有实例,还将提供有关实例类型和各种其他参数的详细信息。

The Script runs across all AWS regions and calls DescribeInstances() , to get the instances. 该脚本跨所有 AWS 区域运行并调用DescribeInstances()以获取实例。

You just need to create a lambda function with run-time nodejs .您只需要使用运行时nodejs创建一个 lambda 函数。 You can even create API out of it and use it as and when required.您甚至可以从中创建 API 并在需要时使用它。

Additionally, You can see AWS official Docs For DescribeInstances to explore many more options.此外,您可以查看 AWS 官方文档,了解DescribeInstances以探索更多选项。

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:该脚本假定凭证配置文件存储在文件~/.aws/credentials中,类似于:

[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

A quick bash oneliner command to print all the instance IDs in all regions:一个快速的bash oneliner命令,用于打印所有区域中的所有实例 ID:

$ aws ec2 describe-regions --query "Regions[].{Name:RegionName}" --output text |xargs -I {} aws ec2 describe-instances --query Reservations[*].Instances[*].[InstanceId] --output text --region {}

# Example output
i-012344b918d75abcd
i-0156780dad25fefgh
i-0490122cfee84ijkl
...

AWS has recently launched the Amazon EC2 Global View with initial support for Instances, VPCs, Subnets, Security Groups, and Volumes. AWS 最近推出了 Amazon EC2 Global View,初步支持实例、VPC、子网、安全组和卷。

To see all running instances go to EC2 or VPC console and click EC2 Global View in the top left corner.要查看所有正在运行的实例,请转到 EC2 或 VPC 控制台,然后单击左上角的EC2 Global View

在此处输入图像描述

Then click on Global Search tab and filter by Resource type and select Instance .然后单击Global Search选项卡并按Resource type过滤并选择Instance Unfortunately, this will show instances in all states:不幸的是,这将显示所有状态的实例:

pending
running
stopping
stopped
shutting-down
terminated

在此处输入图像描述

I created an open-source script that helps you to list all AWS instances.我创建了一个开源脚本,可以帮助您列出所有 AWS 实例。 https://github.com/Appnroll/aws-ec2-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:这是脚本的一部分,它列出了一个配置文件的实例,将它们记录到 postgreSQL 数据库中,并使用jq进行 json 解析:

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

To run jobs in parallel and use multiple profiles use this script.要并行运行作业并使用多个配置文件,请使用此脚本。

#!/bin/bash
for i in profile1 profile2
do
    OWNER_ID=`aws iam get-user --profile $i --output text | awk -F ':' '{print $5}'`
    tput setaf 2;echo "Profile : $i";tput sgr0
    tput setaf 2;echo "OwnerID : $OWNER_ID";tput sgr0
    for region in `aws --profile $i ec2  describe-regions --output text | cut -f4`
    do
        tput setaf 1;echo  "Listing Instances in region $region";tput sgr0
        aws ec2 describe-instances --query 'Reservations[*].Instances[*].[Tags[?Key==`Name`].Value , InstanceId]' --profile $i --region $region --output text
    done &
done
wait

Screenshot:截屏:

截屏

Not sure how long this option's been here, but you can see a global view of everything by searching for EC2 Global View不知道这个选项在这里多久了,但是您可以通过搜索EC2 Global View所有内容的全局视图

https://console.aws.amazon.com/ec2globalview/home# https://console.aws.amazon.com/ec2globalview/home#

全局视图搜索

使用bash-my-aws

region-each instances

Based on @hansaplast code I created Windows friendly version that supports multiple profiles as an argument.基于@hansaplast 代码,我创建了支持多个配置文件作为参数的 Windows 友好版本。 Just save that file as cmd or bat file.只需将该文件保存为 cmd 或 bat 文件即可。 You also need to have jq command.您还需要有jq命令。

@echo off 
setlocal enableDelayedExpansion

set PROFILE=%1
IF "%1"=="" (SET PROFILE=default)

echo checkin instances in all regions for %PROFILE% account
FOR /F "tokens=* USEBACKQ" %%F IN (`aws ec2 describe-regions --query Regions[*].[RegionName] --output text --profile %PROFILE%`) DO (
echo === region: %%F
aws ec2 describe-instances --region %%F --profile %PROFILE%| jq ".Reservations[].Instances[] | {type: .InstanceType, state: .State.Name, tags: .Tags, zone: .Placement.AvailabilityZone}"
)

You may use cli tool designed for enumerating cloud resources (cross-region and cross-accounts scan) - https://github.com/scopely-devops/skew您可以使用专为枚举云资源(跨区域和跨帐户扫描)而设计的 cli 工具 - https://github.com/scopely-devops/skew

After short configuration you may use the following code for list all instances in all US AWS regions (assuming 123456789012 is your AWS account number).简短配置后,您可以使用以下代码列出所有美国 AWS 区域中的所有实例(假设 123456789012 是您的 AWS 帐号)。

from skew import scan

arn = scan('arn:aws:ec2:us-*:123456789012:instance/*')
for resource in arn:
    print(resource.data)

Good tool to CRUD AWS resources . CRUD AWS 资源的好工具。 Find [EC2|RDS|IAM..] in all regions.在所有区域中查找 [EC2|RDS|IAM..]。 There can do operations (stop|run|terminate) on filters results.可以对过滤器结果执行操作(停止|运行|终止)。

python3 awsconsole.py ec2 all // return list of all instances
python3 awsconsole.py ec2 all -r eu-west-1
python3 awsconsole.py ec2 find -i i-0552e09b7a54fa2cf --[terminate|start|stop]

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 running instances on Amazon console.我找不到任何方法可以在Amazon控制台上查看所有正在运行的实例。
Is there any way to display all the running instances regardless of region?有什么方法可以显示所有正在运行的实例,而不管其区域是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM