【问题标题】:Not able to get public ip for ec2-instance via boto3 python无法通过 boto3 python 获取 ec2-instance 的公共 IP
【发布时间】:2020-06-17 04:02:29
【问题描述】:

我正在尝试通过 python 程序获取 ec2 信息,但我无法获取公共 ip 地址的值..尽管它附加了公共 ip,但打印为 None(我可以从控制台看到)

我尝试了什么:

inst_id = []
for reserv in res_inst['Reservations']:
    instance = reserv['Instances']
    for inst in instance:
        ip_addr = inst['PrivateIpAddress']
        #print(inst)
        if (ip == ip_addr):
            inst_id = inst['InstanceId']
            inst_type = inst['InstanceType']
            image_id = inst['ImageId']
            vpc_id = inst['VpcId']
            key_name = inst['KeyName']
            #pub_ip = inst[u'PublicIpAddress']
            pub_ip = inst.get(u'PublicIpAddress')
            print(inst_type)
            print(inst_id)
            print(key_name)
            print(vpc_id)
            print(pub_ip)
            print(image_id)
            az = inst['Placement']['AvailabilityZone']
            print(az)
            for s1 in inst['SecurityGroups']:
                sg_name = s1['GroupName']
                print(sg_name)

在上面的代码中,这些语法不适用于公共 ip..它说关键错误

pub_ip = inst[u'PublicIpAddress']
pub_ip = inst['PublicIpAddress']

以下语法有效,但将 None 作为值

pub_ip = inst.get(u'PublicIpAddress')

输出:除了打印为 None 的 print(pub_ip) 之外,我得到了所有值。

我确信当我在上面的代码中打印inst 的整个 json 字符串时,我看到该 json 字典中存在公共 ip 值,但是,当打印它时说 None。

谁能建议我在这里做错了什么...

【问题讨论】:

  • 可能真的没有。当 ec2 位于私有子网时,它不会有公共子网。

标签: python json amazon-web-services amazon-ec2 boto3


【解决方案1】:

块引用

嗨,天哪, 请试试这个...

response= ec2_client.describe_instances()
for reservation in response['Reservations']:            
   for instance in reservation['Instances']:
      print(instance)

希望对您有所帮助.. @r0ck

【讨论】:

    猜你喜欢
    • 2021-07-06
    • 2021-03-01
    • 2012-05-02
    • 1970-01-01
    • 2019-10-06
    • 2020-11-03
    • 1970-01-01
    • 2011-03-07
    • 2014-10-24
    相关资源
    最近更新 更多