LoginSignup
0
1

More than 1 year has passed since last update.

EC2 インスタンスの特定の情報を収集する

Last updated at Posted at 2021-05-18

素人が自分のノートとして書いてますが、改善点あれば是非コメントください

リージョン指定

ec2クライアント定義時に、region_name = 'us-west-2' 。

lambda-python38
import json
import boto3

def lambda_handler(event, context):

    #ec2 client を定義、引数の region_name = 'xxx' でリージョン指定。
    ec2client = boto3.client('ec2', region_name = 'us-west-2')

    #describe した値を response に入力
    response = ec2client.describe_instances()

    #response を出力
    print(response) 

Describeで出力される順番を使った特定のインスタンスを指定。

response['Reservations'][x]["Instances"][y] の様に辞書型の要素番号で指定。1つ目は0。
ちなみに、Instances の中に複数Instanceは含まれないので基本的に y=0。
それぞれの Instance は x の値で指定する。

lambda-python38
import json
import boto3

def lambda_handler(event, context):

    #ec2 client を定義、引数の region_name = 'xxx' でリージョン指定。
    ec2client = boto3.client('ec2', region_name = 'ap-northeast-1')

    #describe した値を response に入力
    response = ec2client.describe_instances()
    print("response=",response)

    #Reservations の1つ目の要素を抽出。ただし、Reservations には group[]が含まれる。
    reservation0 = response['Reservations'][0]
    print("reservation0=", reservation0)

    #Reservations の1つ目の要素の中のさらに、Instances の中の1つ目の要素=1つ目のEC2インスタンスの情報だけ抽出。
    instance0 = response['Reservations'][0]["Instances"][0]
    print("instance0=", instance0)   

    #Reservations の4つ目の要素の中のさらに、Instances の中の1つ目の要素=4つ目のEC2インスタンスの情報だけ抽出。
    instance3 = response['Reservations'][3]["Instances"][0]
    print("instance3=", instance3)   

特定インスタンスの特定項目(InstanceTypeとか)だけを指定。

instance0['InstanceType'] のような形式で。

lambda-python38
import json
import boto3

def lambda_handler(event, context):

    #ec2 client を定義
    ec2client = boto3.client('ec2')

    #describe した値を response に入力
    response = ec2client.describe_instances()
    print("response=",response)

    #Reservations の1つ目の要素を抽出。ただし、Reservations には group[]が含まれる。
    reservation0 = response['Reservations'][0]
    print("reservation0=", reservation0)

    #Reservations の1つ目の要素の中のさらに、Instances の中の1つ目の要素=1つ目のEC2インスタンスの情報だけ抽出。
    instance0 = response['Reservations'][0]["Instances"][0]

    #instance0 に入力したインスタンスの InstanceType を抽出
    instance0_type = instance0['InstanceType']
    print("instance0_type=", instance0_type)
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1