Python导出aws ec2主机列表到csv文件

1. 背景

需要将AWS EC2主机批量导出到csv文件

Python3 导入所需包: boto3 csv

AWS: AK/SK 在aws控制台IAM中获取下载

2. Python脚本

import boto3
import csv
 
ec2 = boto3.client(
    'ec2',
    aws_access_key_id="xxxx",
    aws_secret_access_key="xxxx",
    region_name='ap-east-1',
    )
 
# Retrieves all regions/endpoints that work with EC2
# response = ec2.describe_regions()
# print('Regions:', response['Regions'])
 
# Retrieves availability zones only for region of the ec2 object
# response = ec2.describe_availability_zones()
# print('Availability Zones:', response['AvailabilityZones'])
 
response = ec2.describe_instances()
with open ("ec2.csv", "w", newline="") as csvf:
    writer = csv.writer(csvf)
    csv_head = ["创建时间", "外网IP", "内网IP", "地区", "Name"]
    writer.writerow(csv_head)
    for i in response["Reservations"]:
        for j in i['Instances']:
            if 'PublicIpAddress' not in j:
                j['PublicIpAddress'] = ""
            if 'Tags' not in j:
                j['Tags'] = []
            for dic in j['Tags']:
                k, v = dic.values()
            row_cvs = [j['LaunchTime'], j['PublicIpAddress'], j['PrivateIpAddress'], 'ap-east-1', v]
            writer.writerow(row_cvs)
 
            print(j['LaunchTime'], j['PublicIpAddress'], j['PrivateIpAddress'], 'ap-east-1', v)

3.效果预览

Python导出aws ec2主机列表到csv文件_第1张图片
参考:

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.describe_instances

或者使用命令:

aws ec2 describe-instances --filters Name=instance-state-name,Values=running

你可能感兴趣的:(python基础及实践,python,aws,开发语言)