AWS CLI V2로 테스트 한 코드
import boto3
import json
ec2_client = boto3.client(
'ec2',
aws_access_key_id = '**************',
aws_secret_access_key = '*********************',
region_name = 'ap-northeast-2'
)
response = ec2_client.describe_instances()
for reservation in response['Reservations']:
for ec2 in reservation['Instances']:
re_tags = {}
if 'Tags' not in ec2:
# Case) all tags removed
#print(ec2["InstanceId"]+'\t'+ec2['InstanceType']+'\t'+ec2['State']['Name']+'\t')
#print('');
pass
else: # Check if tags exist
for tag in ec2['Tags']:
# tag rearrange
re_tags[tag['Key']] = tag['Value']
# Check if "Name" tag exists
if 'Name' in re_tags:
# Check if "Name" tag not null
if re_tags['Name'] != '':
if re_tags['Name'] == tag['Value']:
print(ec2["InstanceId"]+'\t'+ec2['InstanceType']+'\t'+ec2['State']['Name']+'\t'+tag['Value'])
# Debug print
#print(re_tags)
#print(tag['Key'])