获取要在Python中对应的EC2区域和区域

时间:2019-03-11 18:26:53

标签: python boto3

我正在尝试提取一个AWS EC2实例列表。我需要从每个AWS区域和区域中提取实例列表。

我遇到的问题:

  1. 仅需要分别从相应的区域和区域中提取实例 环。
  2. Ec2实例,区域和区域必须对应且必须是 准确。

当前,我的脚本提取了一个实例列表,但相关性是无稽之谈。例如:

-------------------------------------
Instance ID: i-6143add1
Type: m4.2xlarge
State: stopped
Private IP: 10.1.232.175
Public IP: None
Region: eu-north-1
Availability Zone: us-east-1a
Launch Time: February 08 2016
-----------------------------------

由脚本输出。但是实例ID:i-6143add1确实位于us-east-1a区域中,显然可用区us-east-1a不在eu-north-1区域。

如何获取数据?这是我的代码:

#!/usr/bin/env python

import boto3
import collections
from collections import defaultdict
import time
from datetime import datetime
from colorama import init, deinit, Fore, Back, Style
import csv


init()
print(Fore.YELLOW)
aws_account = input("Enter the name of the AWS account you'll be working in: ")
session = boto3.Session(profile_name=aws_account)
ec2 = session.client('ec2')
aws_regions = ec2.describe_regions()
aws_azs = ec2.describe_availability_zones()
ec2info = defaultdict()
for region in aws_regions['Regions']:
    region_name = region['RegionName']
    for az in aws_azs['AvailabilityZones']:
        zone = az['ZoneName']
        instance_list = ec2.describe_instances()
        for reservation in instance_list["Reservations"]:
            for instance in reservation.get("Instances", []):
                private_ip_address = instance.get("PrivateIpAddress" , None)
                public_ip_address = instance.get("PublicIpAddress" , None)
                instance_state = instance['State']['Name']
                if  private_ip_address and public_ip_address:
                    launch_time = instance['LaunchTime']
                    launch_time_friendly = launch_time.strftime("%B %d %Y")
                    ec2info[instance['InstanceId']] = {
                        'Instance ID': instance['InstanceId'],
                        'Type': instance['InstanceType'],
                        'State': instance_state,
                        'Private IP': instance['PrivateIpAddress'],
                        'Public IP': instance['PublicIpAddress'],
                        'Region': region_name,
                        'Availability Zone': zone,
                        'Launch Time' : launch_time_friendly
                    }
                    attributes = ['Instance ID', 'Type',
                                    'State', 'Private IP', 'Public IP', 'Region', 'Availability Zone', 'Launch Time' ]
                    for instance_id, instance in ec2info.items():
                        print(Fore.RESET + "-------------------------------------")
                        for key in attributes:
                            print(Fore.CYAN + "{0}: {1}".format(key, instance[key]))
                            writer.writerow({'Instance ID': key, 'Type': key, 'Launch Time': key})
                        print(Fore.RESET + "-------------------------------------")
                elif private_ip_address:
                    launch_time = instance['LaunchTime']
                    launch_time_friendly = launch_time.strftime("%B %d %Y")
                    ec2info[instance['InstanceId']] = {
                        'Instance ID': instance['InstanceId'],
                        'Type': instance['InstanceType'],
                        'State': instance_state,
                        'Private IP': instance['PrivateIpAddress'],
                        'Public IP': None,
                        'Region': region_name,
                        'Availability Zone': zone,
                        'Launch Time' : launch_time_friendly
                    }
                    attributes = ['Instance ID', 'Type',
                                    'State', 'Private IP', 'Public IP', 'Region', 'Availability Zone', 'Launch Time' ]
                    for instance_id, instance in ec2info.items():
                        print(Fore.RESET + "-------------------------------------")
                        for key in attributes:
                            print(Fore.CYAN + "{0}: {1}".format(key, instance[key]))
                        print(Fore.RESET + "-------------------------------------")

2 个答案:

答案 0 :(得分:1)

您没有将任何过滤选项传递给describe_instances,因此您将一遍又一遍地找回所有实例。您可能想要类似的东西

instance_list = ec2.describe_instances(
    Filters=[{"Name": "availability-zone", "Values": [zone]}]
)

...虽然说实话,但没有理由重复AZ,因为您可以在reservation['Instances'][...]['Placement']['AvailabilityZone']中获得相同的信息,就像您在the Boto3 docs here中看到的一样。


编辑:我认为您可以简单地通过

#!/usr/bin/env python

import boto3
from colorama import init, deinit, Fore, Back, Style

print(Fore.YELLOW)
aws_account = input(
    "Enter the name of the AWS account you'll be working in: "
)
session = boto3.Session(profile_name=aws_account)
ec2 = session.client("ec2")
ec2info = {}
instance_list = ec2.describe_instances()
for reservation in instance_list["Reservations"]:
    for instance in reservation.get("Instances", []):
        instance_state = instance["State"]["Name"]
        launch_time = instance["LaunchTime"]
        launch_time_friendly = launch_time.strftime("%B %d %Y")
        ec2info[instance["InstanceId"]] = {
            "Instance ID": instance["InstanceId"],
            "Type": instance["InstanceType"],
            "State": instance_state,
            "Private IP": instance["PrivateIpAddress"],
            "Public IP": instance["PublicIpAddress"],
            "Region": instance["Placement"]["AvailabilityZone"][:-2],
            "Availability Zone": instance["Placement"]["AvailabilityZone"],
            "Launch Time": launch_time_friendly,
        }

for instance_id, instance in ec2info.items():
    print(Fore.RESET + "-------------------------------------")
    for key in [
        "Instance ID",
        "Type",
        "State",
        "Private IP",
        "Public IP",
        "Region",
        "Availability Zone",
        "Launch Time",
    ]:
        print(Fore.CYAN + "{0}: {1}".format(key, instance.get(key)))
    print(Fore.RESET + "-------------------------------------")

答案 1 :(得分:1)

获取此信息的一种非常简单的方法是:

res = requests.get(' http://169.254.169.254/latest/dynamic/instance-identity/document')

data = json.loads(res.text)

print(data)

print(data['region'])

print(data['instanceId'])