简体   繁体   English

获取 EC2 区域和区域以在 Python 中对应

[英]Get EC2 Regions and Zones to correspond in Python

I'm trying to pull a list of AWS EC2 instances.我正在尝试提取 AWS EC2 实例列表。 I need to pull a list of instances from each AWS zone and region.我需要从每个 AWS 区域和区域中提取实例列表。

Problems I'm having:我遇到的问题:

  1. Need to pull instances only from corresponding zone and region each loop.每个循环只需要从相应的区域和区域中提取实例。
  2. Ec2 Instance, zone and region has to correspond and be accurate. Ec2 Instance, zone 和 region 必须对应且准确。

Currently my script pulls a list of instances, but the correlation is nonsense.目前我的脚本提取了一个实例列表,但相关性是无稽之谈。 For example:例如:

-------------------------------------
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
-----------------------------------

Is output by the script.是脚本的输出。 But instance ID: i-6143add1 is really in region us-east-1a, and obviously availability zone us-east-1a is not in region eu-north-1.但是实例 ID:i-6143add1 确实在区域 us-east-1a 中,显然可用区 us-east-1a 不在区域 eu-north-1 中。

How can I get the data to line up?我怎样才能让数据排队? Here is my code:这是我的代码:

#!/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 + "-------------------------------------")

You aren't passing any filtering options to describe_instances so you're getting back all of your instances over and over again.您没有向describe_instances传递任何过滤选项,因此您一遍又一遍地取回所有实例。 You probably want something like你可能想要类似的东西

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

... though in all honesty there's no reason to iterate over the AZs, as you can get that same information in reservation['Instances'][...]['Placement']['AvailabilityZone'] , as you can see in the Boto3 docs here . ...虽然老实说没有理由遍历 AZ,因为您可以在 reserved reservation['Instances'][...]['Placement']['AvailabilityZone']获得相同的信息,如您所见在此处的 Boto3 文档中


EDIT: I think you could get by simply with something like编辑:我认为你可以简单地使用类似的东西

#!/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 + "-------------------------------------")

A very simple way to get this info is:获取此信息的一种非常简单的方法是:

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'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM