【问题标题】:How to see all running Amazon EC2 instances across all regions?如何查看所有区域中所有正在运行的 Amazon EC2 实例?
【发布时间】:2017-06-24 12:17:19
【问题描述】:

我经常在不同区域之间切换实例,有时我忘记关闭来自不同区域的正在运行的实例。我找不到任何方法可以在 Amazon 控制台上查看所有正在运行的实例。
有什么方法可以显示所有正在运行的实例而不考虑区域?

【问题讨论】:

  • AWS GUI 不只是让您列出所有实例的事实真的非常愚蠢。
  • 不理想也绝对不明显,但您可以使用 Resource Groups > Tag Editor 作为 GUI 选项。请参阅下面的答案。
  • @DanDascalescu 你确定吗?你认为 AWS 从像 OP 这样忘记关闭正在运行的实例的人那里赚了多少钱?
  • @DanDascalescu as smartcaveman 说,如果实例散布在许多地区并被遗忘,而贝佐斯的 $ticker 滴答滴答滴答作响,这将是愚蠢的。
  • @DanDascalescu 如果他们只是显示正在运行的内容,他们将如何向忘记实例的人收费..?

标签: amazon-web-services amazon-ec2 ec2-ami


【解决方案1】:

我认为您目前无法在 AWS GUI 中执行此操作。但这是一种使用 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

取自here(如果你想看到完整的讨论)

另外,如果你得到一个

您必须指定一个区域。您还可以通过运行“aws configure”来配置您的区域

您可以使用aws configure set region us-east-1 进行操作,感谢@Sabuncu 的评论。

更新

现在(2019 年)应该在第 4 个字段上应用剪切命令:cut -f4

【讨论】:

  • 为了避免cut,可以使用:aws ec2 describe-regions --query Regions[*].[RegionName] --output text
  • 如果使用配置文件,请将 --profile profile-name 添加到 both 的 aws ec2 命令。
  • 您可以在 Windows 10 CMD 上使用此命令,FOR /F %G IN ('aws ec2 describe-regions --query Regions[*].[RegionName] --output text') DO (aws ec2 describe-instances --region %G)
  • 这似乎不起作用 -- You must specify a region. You can also configure your region by running "aws configure". -- 似乎指定一个区域与我想要做的相反
  • @WillSheppard 您必须先配置您的区域;例如aws configure set region us-east-1。然后,当您运行aws ec2 describe-regions 时,您应该没有问题。请参阅答案:stackoverflow.com/a/46577479/360840 以及相关问题下的其他答案。
【解决方案2】:

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

【讨论】:

  • 这就是这样做的方法。没有疯狂的循环或多个查询。资源组将为您整合所有内容!
【解决方案3】:

您可以在所有地区运行DescribeInstances()

此外,您还可以:

  • 通过 Lambda 和 Cloud watch 实现自动化。
  • 使用 Lambda 和 api 网关创建 api 端点并在您的代码中使用它

NodeJS 中的一个示例:

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

    regionNames.forEach(功能(区域){
        获取实例(区域);
    });

  • 那么,在getInstances函数中,DescribeInstances()可以 调用。
函数getInstances(区域){
            EC2.describeInstances(参数,函数(错误,数据){
                if (err) return console.log("连接 AWS 时出错,未找到此类实例!");
                data.Reservations.forEach(function(reservation) {
                //执行任何预期的操作
      });
    }

Off Course,请随意使用 ES6 及更高版本。

我编写了一个 lambda 函数来获取处于任何状态 [运行、停止] 和来自任何区域的所有实例,还将提供有关实例类型和各种其他参数的详细信息。

The Script 在所有 AWS 区域运行并调用 DescribeInstances() 以获取实例。

您只需要创建一个运行时 nodejs 的 lambda 函数。 您甚至可以从中创建 API 并在需要时使用它。

此外,您可以查看 AWS 官方文档 For DescribeInstances 以探索更多选项。

【讨论】:

【解决方案4】:

基于 imTachus 的回答,但不那么冗长,而且速度更快。您需要安装 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

脚本为每个区域(现在是 15 个!)并行运行 aws ec2 describe-instances,并从 json 输出中仅提取相关位(状态、标签、可用区)。需要set +m,以便后台进程在启动/结束时不会报告。

示例输出:

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

【讨论】:

    【解决方案5】:

    基于@hansaplast 代码,我创建了支持多个配置文件作为参数的 Windows 友好版本。只需将该文件保存为 cmd 或 bat 文件即可。您还需要有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}"
    )
    

    【讨论】:

      【解决方案6】:

      @imTachu 解决方案效果很好。要通过 AWS 控制台执行此操作...

      • AWS 控制台
      • 服务
      • 网络和内容交付
      • VPC
      • 寻找一个名为“Running Instances”的区块,它会显示当前区域
      • 点击下方的“查看所有地区”链接

      【讨论】:

      • “服务”下现在没有“网络和内容交付”
      • 在 AWS 控制台中:点击“服务”> 在文本框中输入“vpc”,然后选择 VPC 隔离的云资源
      • 他们又更新了。 EC2 仪表板中现在有一个快捷方式。转到实例部分并单击“实例”。它将显示所选区域中所有正在运行的实例。
      • 对不起,它就在那里!但是您可以直接访问 VPC。 Mindfulgeek - 您错过了重点:EC2 中始终存在“按区域”,但 OP 希望查看所有区域。 VPC方法可以让您查看是否有跨区域
      【解决方案7】:

      2021 年 11 月编辑:AWS 最近推出了 Amazon EC2 Global View,初步支持实例、VPC、子网、安全组和卷。

      请参阅announcementdocumentation 了解更多详情


      一个不明显的 GUI 选项是资源组控制台中的 Tag Editor。在这里,您可以找到所有区域的所有实例,即使这些实例没有被标记。

      【讨论】:

      • 这又变了。我不再在此工具中看到“区域”块。相反,它只显示“当前区域”中的所有内容。上帝只知道设置在哪里......假设我有 20 和 500 台机器的员工,我已经厌倦了这些白痴。
      • @breakpoint 看起来他们现在添加了指向支持多区域搜索的以前的标签编辑器的链接。
      • 伙计,这是救生员!感谢分享! :-D
      • 如果 aws 有一个内置的“所有区域”或类似的下拉菜单,那就太好了
      • @user5783745 屏幕最近已更新,现在有一个“所有区域”选项
      【解决方案8】:

      您可以使用专为枚举云资源而设计的cli工具(跨区域和跨账户扫描)-https://github.com/scopely-devops/skew

      简单配置后,您可以使用以下代码列出所有美国 AWS 区域中的所有实例(假设 123456789012 是您的 AWS 帐号)。

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

      【讨论】:

        【解决方案9】:

        CRUD AWS resources 的好工具。在所有区域中查找 [EC2|RDS|IAM..]。可以对过滤器结果执行操作(停止|运行|终止)。

        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]
        

        【讨论】:

          【解决方案10】:
          1. 首先转到AWS Management console并点击资源组:

          2. 然后找到Network and Content Delivery并点击VPC

          3. 然后找到正在运行的实例并展开查看所有区域。在这里您可以找到所有区域的所有正在运行的实例:

          【讨论】:

          • 此菜单已更改。我找不到正在运行的实例。
          【解决方案11】:

          下面是我的脚本,基于这篇文章和其他地方的各种提示。该脚本比长命令行更容易理解(至少对我而言)。

          脚本假定凭据配置文件存储在文件 ~/.aws/credentials 中,类似于:

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

          脚本:

          #!/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
          

          【讨论】:

          • 如果您还没有这样做,我建议您将这些凭据作废。
          • @Thiago 谢谢,但这些凭据无论如何都是伪造的占位符:)。
          【解决方案12】:

          我创建了一个开源脚本,可帮助您列出所有 AWS 实例。 https://github.com/Appnroll/aws-ec2-instances

          这是脚本的一部分,它列出了一个配置文件的实例,将它们记录到 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
          

          【讨论】:

            【解决方案13】:

            在控制台中

            转到 VPC 仪表板https://console.aws.amazon.com/vpc/home 并点击Running instances -> See all regions

            在 CLI 中

            例如添加到.bashrc。重新加载它source ~/.bashrc,然后运行它

            注意:除了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
            }
            

            示例输出:

            $ 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'..
            

            【讨论】:

            • 在 2021 年,这种 VPC 管理控制台方式是我查找所有运行 EC2 实例的区域的最佳方式。谢谢sobi3ch。
            【解决方案14】:

            要并行运行作业并使用多个配置文件,请使用此脚本。

            #!/bin/bash 对于我在 profile1 profile2 做 OWNER_ID=`aws iam get-user --profile $i --output text | awk -F ':' '{打印 $5}'` tput setaf 2;echo "Profile : $i";tput sgr0 tput setaf 2;echo "OwnerID : $OWNER_ID";tput sgr0 `aws 中的区域 --profile $i ec2 describe-regions --output text |剪切-f4` 做 tput setaf 1;echo "列出区域 $region 中的实例";tput sgr0 aws ec2 describe-instances --query 'Reservations[*].Instances[*].[Tags[?Key==`Name`].Value , InstanceId]' --profile $i --region $region --output text 完毕 & 完毕 等待

            截图:

            【讨论】:

              【解决方案15】:

              在阅读了所有解决方案并尝试了一堆东西之后,对我有用的是-

              1. 列表项
              2. 转到资源组
              3. 标签编辑器
              4. 选择所有地区
              5. 在资源类型中选择 EC2 实例
              6. 点击搜索资源

              【讨论】:

                【解决方案16】:

                一个快速的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
                ...
                

                【讨论】:

                  【解决方案17】:

                  不知道这个选项已经存在多久了,但是你可以通过搜索EC2 Global View来查看所有内容的全局视图

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

                  【讨论】:

                    【解决方案18】:

                    使用bash-my-aws

                    region-each instances
                    

                    【讨论】:

                      猜你喜欢
                      • 2019-11-30
                      • 1970-01-01
                      • 2021-08-13
                      • 1970-01-01
                      • 1970-01-01
                      • 2014-04-09
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      相关资源
                      最近更新 更多