Development Tip

모든 리전에서 실행중인 모든 Amazon EC2 인스턴스를 보려면 어떻게해야합니까?

yourdevel 2020. 10. 23. 19:11
반응형

모든 리전에서 실행중인 모든 Amazon EC2 인스턴스를 보려면 어떻게해야합니까?


다른 지역간에 인스턴스를 자주 전환하고 때로는 다른 지역에서 실행중인 인스턴스를 끄는 것을 잊었습니다. Amazon 콘솔에서 실행중인 모든 인스턴스를 볼 수있는 방법을 찾을 수 없었습니다.
지역에 관계없이 실행중인 모든 인스턴스를 표시하는 방법이 있습니까?


명확하지 않은 GUI 옵션은 Resource Groups > Tag Editor입니다. 여기에서 인스턴스에 태그가 지정되지 않은 경우에도 모든 리전의 모든 인스턴스를 찾을 수 있습니다.화면 캡처


편집 :이 화면은 최근에 재 설계되었으며 이제 새로운 모양과 "모든 지역"옵션이 있습니다.


현재 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 년) 4 번째 필드에 cut 명령을 적용해야합니다. cut -f4


@imTachu 솔루션이 잘 작동합니다. AWS 콘솔을 통해이 작업을 수행하려면 ...

  • AWS 콘솔
  • 서비스
  • 네트워킹 및 콘텐츠 제공
  • VPC
  • "실행중인 인스턴스"라는 이름의 블록을 찾으면 현재 지역이 표시됩니다.
  • 아래의 "모든 지역보기"링크를 클릭하십시오.

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

스크립트는 aws ec2 describe-instances각 지역 (현재 15 개!)에 대해 병렬로 실행 하고 json 출력에서 ​​관련 비트 (상태, 태그, 가용성 영역) 만 추출합니다. set +m백그라운드 프로세스가 시작할 때 / 종료보고하지 않도록 필요합니다.

출력 예 :

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

리소스를 생성 할 때마다 이름으로 태그를 지정하면 이제 리소스 그룹사용 하여 모든 리전에서 이름 태그가있는 모든 유형의 리소스를 찾을 수 있습니다 .


  1. 먼저 AWS Management 콘솔 로 이동하여 리소스 그룹을 클릭합니다.

    여기에 이미지 설명 입력

  2. 그런 다음 다음을 찾아 Network and Content Delivery클릭하십시오 VPC.

    여기에 이미지 설명 입력

  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-east-1 ','ap-southeast-1 ','ap-southeast-2 ','ap-northeast-1 ','ap-northeast-2 '];

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

  • 그런 다음 getInstances함수에서 DescribeInstances()호출 할 수 있습니다.
function getInstances (region) {
            EC2.describeInstances (params, function (err, data) {
                if (err) return console.log ( "AWS에 연결하는 동안 오류가 발생했습니다. 해당 인스턴스를 찾을 수 없습니다!");
                data.Reservations.forEach (function (reservation) {
                // 의도 한 작업 수행
      });
    }

그리고 Off Course는 ES6 이상을 자유롭게 사용하십시오.

어떤 상태 (실행 중, 중지됨)의 모든 인스턴스를 가져오고 모든 리전에서 인스턴스 유형 및 기타 다양한 매개 변수에 대한 세부 정보를 제공하는 람다 함수를 작성했습니다.

스크립트 는 모든 AWS 리전에서 실행되고을 호출 DescribeInstances()하여 인스턴스를 가져옵니다.

run-time으로 람다 함수를 생성하기 만하면됩니다 nodejs. API를 만들어 필요할 때 사용할 수도 있습니다.

또한 AWS 공식 DescribeInstances 문서를 참조 하여 더 많은 옵션을 탐색 할 수 있습니다.


모든 AWS 인스턴스를 나열하는 데 도움이되는 오픈 소스 스크립트를 만들었습니다. https://github.com/Appnroll/aws-ec2-instances

이는 jqjson 구문 분석 을 사용하여 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

이 게시물 및 다른 곳의 다양한 팁을 기반으로 한 아래 내 스크립트. 스크립트는 긴 명령 줄보다 (적어도 나를 위해) 따라 가기가 더 쉽습니다.

스크립트는 자격 증명 프로필이 ~/.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

콘솔에서

VPC 대시 보드로 이동하여 ->를 console.aws.amazon.com/vpc/home클릭하십시오 .Running instancesSee all regions

여기에 이미지 설명 입력

CLI에서

예를 들어 이것을 .bashrc. 다시로드 source ~/.bashrc하고 실행합니다.

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

Based on @hansaplast code I created Windows friendly version that supports multiple profiles as an argument. Just save that file as cmd or bat file. You also need to have jq command.

@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

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).

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. Find [EC2|RDS|IAM..] in all regions. 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]

참고URL : https://stackoverflow.com/questions/42086712/how-to-see-all-running-amazon-ec2-instances-across-all-regions

반응형