끄적이는 보송

[Python] EC2 Instance 리스트 조회하여 필요한 정보 CSV로 추출하기 본문

STUDY/스크립트&코드

[Python] EC2 Instance 리스트 조회하여 필요한 정보 CSV로 추출하기

끄적이는 보송 2023. 2. 15. 10:56
반응형

Python으로 EC2 Instance의 Name, ID, Private IP, Public IP를 조회하여 CSV파일로 추출하는 코드

import boto3
import csv

YOUR_REGION = 'ap-northeast-2'

# Create an EC2 client
ec2 = boto3.client('ec2', region_name=YOUR_REGION)

# Retrieve all instances (both running and stopped)
instances = ec2.describe_instances()

# Create a list to hold the instance details
instance_details = []

# Append the details of each instance to the list
for reservation in instances['Reservations']:
    for instance in reservation['Instances']:
        instance_id = instance['InstanceId']
        name = ''
        for tag in instance['Tags']:
            if tag['Key'] == 'Name':
                name = tag['Value']
                break
        private_ip_address = instance.get('PrivateIpAddress', '')
        public_ip_address = instance.get('PublicIpAddress', '')
        instance_details.append({'Name': name, 'Instance ID': instance_id, 'Private IP': private_ip_address, 'Public IP': public_ip_address})

# Write the instance details to a CSV file
with open('instance_details.csv', 'w', newline='') as file:
    writer = csv.DictWriter(file, fieldnames=['Name', 'Instance ID', 'Private IP', 'Public IP'])
    writer.writeheader()
    for instance in instance_details:
        writer.writerow(instance)
반응형
Comments