如何打印EC2标签名称和IP地址?

时间:2016-06-08 03:57:23

标签: python amazon-ec2 boto3

我有一个代码可以打印正在运行的实例的公共IP,

regions = ['us-east-1','us-west-1','us-west-2','eu-west-1','sa-east-1','ap-southeast-1','ap-southeast-2','ap-northeast-1']
for region in regions:
  client = boto3.client('ec2',aws_access_key_id=ACCESS_KEY,aws_secret_access_key=SECRET_KEY,region_name=region,)
  addresses_dict = client.describe_addresses()
  for eip_dict in addresses_dict['Addresses']:
      if 'PrivateIpAddress' in eip_dict:
          print eip_dict['PublicIp']

这很好,现在我也要打印tag name并将其存储在另一个字典中,我知道我可以通过以下方式完成:

regions = ['us-east-1','us-west-1','us-west-2','eu-west-1','sa-east-1','ap-southeast-1','ap-southeast-2','ap-northeast-1']
for region in regions:
  client = boto3.client('ec2',aws_access_key_id=ACCESS_KEY,aws_secret_access_key=SECRET_KEY,region_name=region,)
  dex_dict = client.describe_tags()
  for dexy_dict in dex_dict['Tags']:
     print dexy_dict['Value']

问题是如何将它组合在一个函数中并使用2个dict:一个用于存储IP,另一个用于存储标记名称?请帮助

1 个答案:

答案 0 :(得分:0)

尝试以下代码,它会为您提供一个字典,其中键为InstanceId,值为[PublicIP, Name]列表。

import boto3

def instance_info():
    instance_information = {}
    ip_dict = {}
    client = boto3.client('ec2')
    addresses_dict = client.describe_addresses().get('Addresses')

    for address in addresses_dict:
        if address.get('InstanceId'):
            instance_information[address['InstanceId']] = [address.get('PublicIp')]

    dex_dict = client.describe_tags().get('Tags')
    for dex in dex_dict:
        if instance_information.get(dex['ResourceId']):
            instance_information[dex['ResourceId']].append(dex.get('Value'))

    for instance in instance_information:

        if len(instance_information[instance]) == 2:
            ip_dict[instance_information[instance][0]] = instance_information[instance][1]
        else:
            ip_dict[instance_information[instance][0]] = ''
    return instance_information, ip_dict