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


我认为目前在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

从这里开始(如果你想看完整的讨论)

另外,如果你得到一个

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

你可以通过aws配置set region us-east-1来实现,谢谢@Sabuncu的评论。

更新

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


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


您可以跨所有区域运行descripbeinstances()。

此外,你可以:

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

NodeJS中的示例:

创建一个区域(端点)数组。[也可以使用AWS描述区域()]

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);
    });

然后,在getInstances函数中,descripbeinstances()可以是 调用。

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
      });
    }

当然,你可以随意使用ES6及以上版本。

我写了一个lambda函数来获得任何状态[正在运行,停止]和任何区域的所有实例,还将给出关于实例类型和各种其他参数的详细信息。

脚本在所有AWS区域运行,并调用descripbeinstances()来获取实例。

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

此外,您可以查看AWS官方文档用于描述实例,以探索更多选项。


基于imTachus的答案,但更少的啰嗦,加上更快。您需要安装jq和aws-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 description -instances,并仅从json输出中提取相关的位(状态、标签、可用分区)。需要set +m,以便后台进程在启动/结束时不报告。

示例输出:

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

基于@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}"
)

@imTachu解决方案效果很好。要通过AWS控制台做到这一点…

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


编辑:AWS最近推出了亚马逊EC2全球视图,初步支持实例、vpc、子网、安全组和卷。

详情请参阅公告或文档


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


您可以使用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)

CRUD AWS资源的好工具。找到(EC2 | RDS |我. .]在所有地区。可以对过滤结果执行操作(stop|run|terminate)。

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]

来自VPC Dashboard:

首先进入“VPC面板” 然后找到正在运行的实例并展开“查看所有区域”。在这里你可以找到所有区域的运行实例:

EC2全球视角:

您还可以使用AWS EC2全局视图来查看资源摘要 和每个区域的资源计数。


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

脚本假设凭据概要文件存储在文件~/中。Aws /凭证看起来像这样:

[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

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

这是脚本的一部分,列出了一个配置文件的实例,并使用jq进行json解析,将它们记录到postgreSQL数据库中:

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

在控制台

进入VPC面板https://console.aws.amazon.com/vpc/home,单击“运行实例”。->查看所有区域。

在CLI

例如,将此添加到.bashrc。重新加载源代码~/。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'..

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

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

截图:


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

列表项 进入资源组 标签编辑器 选择所有区域 在资源类型中选择“EC2实例” 单击“搜索资源”


一个快速bash onlineer命令,打印所有区域的所有实例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
...

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

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


使用bash-my-aws:

region-each instances

AWS最近推出了Amazon EC2全球视图,最初支持实例、vpc、子网、安全组和卷。

进入EC2或VPC控制台,单击左上角的“EC2全局视图”,查看所有正在运行的实例。

然后单击“全局搜索”选项卡,按资源类型筛选并选择实例。不幸的是,这将显示所有状态的实例:

pending
running
stopping
stopped
shutting-down
terminated