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

我经常在不同的区域之间切换实例,有时我会忘记关闭在不同地区正在运行的实例。我找不到任何方法来查看亚马逊控制台上所有正在运行的实例 是否有任何方法可以显示所有区域正在运行的所有实例?< / p >
112698 次浏览

我认为目前在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 configure set region us-east-1这样做,谢谢@Sabuncu的评论。

更新

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

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

你可以在所有地区运行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-east-1', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ap-northeast-2'];


regionNames.forEach(function(region) {
getInstances(region);
});


  • 则在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
});
}

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

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

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

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

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

基于imTachus的答案,但更少的啰嗦,加上更快。你需要安装金桥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 describe-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”的块,这将显示您当前的区域
  • 点击下方的“查看所有区域”链接

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

更多细节请参见公告文档


一个不明显的GUI选项是资源组控制台中的标签编辑器。在这里,您可以找到所有区域的所有实例,即使这些实例没有被标记。 屏幕截图 < / p >

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

  1. 首先去VPC仪表板

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

    enter image description here

EC2全局视图:

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

该脚本假设凭据配置文件存储在~/.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

我创建了一个开源脚本,可以帮助您列出所有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

在控制台

进入VPC仪表板https://console.aws.amazon.com/vpc/home,单击Running instances ->See all regions

enter image description here

在CLI

例如,将此添加到.bashrc。重新加载source ~/.bashrc,并运行它

注意:除了aws CLI,你需要安装金桥

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

截图:

截图

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

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

Snapshot of the solution

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

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

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

Global View Search .

使用bash-my-aws:

region-each instances

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

进入EC2或VPC控制台,单击左上角的EC2 Global View,查看所有正在运行的实例。

enter image description here

然后单击Global Search选项卡,通过Resource type筛选并选择Instance。不幸的是,这将显示所有状态的实例:

pending
running
stopping
stopped
shutting-down
terminated

enter image description here