如何使用BOTO python在AWS中获取实例的公共dns

时间:2011-07-12 21:17:37

标签: python amazon-web-services boto

我得到一个特定地区的elb细节说欧洲然后我能够获得与ELB相关的实例。问题是我无法获得这些实例的公共dns。我做的是

conn = regions[3].connect(aws_access_key_id= access, aws_secret_access_key = secret_key)
loadbalancers = conn.get_all_load_balancers()
for lb in loadbalancers:
print lb.instances

如何获取这些实例的public_dns_name

当我尝试

for i in lb.instances:
    i.public_dns_name

AttributeError:'InstanceInfo'对象没有属性'public_dns_name'

1 个答案:

答案 0 :(得分:9)

LoadBalancer类的“instances”属性仅包含有关该实例的一小部分信息 - 它不是一个完整的Instance对象。要获取完整实例对象,必须使用可用的instanceId来查询更多信息。此代码段使用所需的调用扩展您的代码:

#Create connection to ec2, credentials stored in environment
ec2_conn = connect_ec2()

conn = regions[3].connect(aws_access_key_id= access, aws_secret_access_key = secret_key)
loadbalancers = conn.get_all_load_balancers()
for lb in loadbalancers:
    for i in lb.instances:
        #Here, 'i' is an InstanceInfo object, not a full Instance
        instance_id = i.id

        #Query based on the instance_id we've got
        #This function actually gives reservations, not instances
        reservations = ec2_conn.get_all_instances(instance_ids=[instance_id])
        #pull out our single instance
        instance = reservations[0].instances[0]

        #Now we've got the full instance and we can get parameters from here
        print(instance.public_dns_name)