hisosic

boto3 리전 별 EC2 Instance 전체 정보 가져오기 (ID,Type,EBS,TAG) 본문

Cloud/AWS

boto3 리전 별 EC2 Instance 전체 정보 가져오기 (ID,Type,EBS,TAG)

hisosic 2023. 2. 21. 17:18

1. Source

~]$ cat boto3_ec2_all_listing.py

#!/usr/bin/env python3
import boto3
import argparse
import sys

def get_tag(resource, region):
    EC2_RESOURCE = boto3.resource(resource, region)
    instances = EC2_RESOURCE.instances.all()
    for instance in instances:
        print(f'EC2 instance {instance.id}" information:')
        print(f'Instance state: {instance.state["Name"]}')
        print(f'Instance AMI: {instance.image.id}')
        print(f'Instance platform: {instance.platform}')
        print(f'Instance type: "{instance.instance_type}')
        print(f'Public IPv4 address: {instance.public_ip_address}')
        print(f'Volumes attached to the EC2 instance:')
        device_mappings = instance.block_device_mappings
        for device in device_mappings:
            print(f"  - Volume {device['Ebs']['VolumeId']} attached as {device['DeviceName']}")
        print(f'EC2 instance {instance.id} tags:')
        if len(instance.tags) > 0:
            for tag in instance.tags:
                print(f'  - Tag: {tag["Key"]}={tag["Value"]}')
        else:
            print(f'  - No Tags')

        print('-'*60)



if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Commander')
    parser.add_argument('-t', '--resource', default="ec2", help='resource_name', choices=['ec2', 'ebs'])
    parser.add_argument('-r', '--region', default="ap-northeast-2", help='region_code')

    args = parser.parse_args()

    get_tag(args.resource, args.region)

 

2. Start

~]$ boto3_ec2_all_listing.py -r ap-northeast-1

~]$ boto3_ec2_all_listing.py -r us-east-1

 

 

3. Result

------------------------------------------------------------
EC2 instance i-010exxxxxxxxxx" information:
Instance state: running
Instance AMI: ami-753a971b
Instance platform: None
Instance type: "m5.xlarge
Public IPv4 address: 13.125.xx.xxx
Volumes attached to the EC2 instance:
  - Volume vol-0333xxxx34565ed38 attached as /dev/sda1
EC2 instance i-010exxxxxxxxxx tags:
  - Tag: OperatingSystem=
  - Tag: Product=Infra
  - Tag: Team=Infra
  - Tag: Age Limit=
  - Tag: Name=jmonServer
  - Tag: Role=mgmt
  - Tag: Env=Mgmt
  - Tag: INFO=BTP,SEJONGNET - MON
  - Tag: User=xxxx
------------------------------------------------------------
EC2 instance i-0a6xxxxxxxxxxxx" information:
Instance state: running
Instance AMI: ami-424ce32c
Instance platform: None
Instance type: "t3.medium
Public IPv4 address: 13.124.xx.xxx
Volumes attached to the EC2 instance:
  - Volume vol-03b3xxxx3d85ac85f attached as /dev/sda1
EC2 instance i-0a6xxxxxxxxxxxx" tags:
  - Tag: OperatingSystem=
  - Tag: Product=Infra
  - Tag: Env=GW
  - Tag: Team=Infra
  - Tag: AgeLimit=
  - Tag: User=Infra
  - Tag: USE_OTP=yes
  - Tag: Role=gw
  - Tag: Name=T_GW01
------------------------------------------------------------​

 

 

 

 

Comments