1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

全EC2のタグ情報を取得しJSON形式にするメモ

Last updated at Posted at 2021-09-20

はじめに

AWS EC2 のタグ情報を取得し、JSON形式にするPython3.9スクリプト
EC2タグ情報を、SDK(boto3)の describe_instances() で取得しました。

describe_instances()で一度に取得できる情報は最大1000のようで、1001以降の情報を取得するには、NextToken を使用するようです。

スクリプト

  • 処理概要
    • 全てのEC2タグ情報を取得するためNextTokenの処理を記載
    • 取得した情報を変数 ec2tagsjson にJSON形式で格納
    • ただし、タグキーが aws: から始まる情報は、取得対象から除外
getEc2TagsInfo.py
import boto3
import sys

# python バージョン確認
if sys.version_info >= (3,8):
    print('Python Version Check [OK] : {0}'.format(sys.version_info) )
else:
    print('Python Version Check [NG] : {0}'.format(sys.version_info) )
    exit()

client = boto3.client('ec2')

ec2tagsjson = {}
NextToken = None
while True:
    if NextToken is None:
        ec2_info = client.describe_instances()
    else:
        ec2_info = client.describe_instances(NextToken=NextToken)

    for Reservations in ec2_info['Reservations']:
        for instances in Reservations['Instances']:
            tagsjson = {}
            for tag in instances['Tags']:
                if tag["Key"].find('aws:') != 0:
                    tagsjson[ tag["Key"] ] = tag["Value"]
            ec2tagsjson[ str(instances['InstanceId']) ] = tagsjson

    if not 'NextToken' in ec2_info:
        break
    NextToken = ec2_info['NextToken']

print(ec2tagsjson)

実行結果例

JSON形式で、インスタンスIDごとにタグ情報をまとめた情報が表示されます。

$ python getEc2TagsInfo.py
Python Version Check [OK] : sys.version_info(major=3, minor=9, micro=4, releaselevel='final', serial=0)
{'i-00000000000000001': {'test2': 'test2Val', 'Name': 'HOGE', 'test1': 'test1Val'}}

インスタンスIDが、i-00000000000000001 のEC2に付与された3つのタグの情報をJSON形式で表示しています。


1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?