使用BOTO3检索EC2实例的公共DNS [英] Retrieving public dns of EC2 instance with BOTO3

查看:135
本文介绍了使用BOTO3检索EC2实例的公共DNS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ipython了解Boto3并与EC2实例进行交互。这是我用来创建实例的代码:

I'm using ipython to get an understanding of Boto3 and interacting with EC2 instances. Here is the code I'm using to create an instance:

import boto3

ec2 = boto3.resource('ec2')
client = boto3.client('ec2')


new_instance = ec2.create_instances(
    ImageId='ami-d05e75b8',
    MinCount=1,
    MaxCount=1,
    InstanceType='t2.micro',
    KeyName=<name_of_my_key>,
    SecurityGroups=['<security_group_name>'],
    DryRun = False
    )

这将启动EC2实例很好,我可以从AWS控制台获取公共DNS名称,ip和其他信息。但是,当我尝试使用Boto获取公共DNS时,可以这样做:

This starts an EC2 instance fine, and I can get the public DNS name, ip and other info from the AWS console. But, when I try to get the public DNS using Boto, by doing this:

new_instance[0].public_dns_name

返回空引号。但是,其他实例详细信息,例如:

Returns blank quotes. Yet, other instance details, such as:

new_instance[0].instance_type

返回正确的信息。

有什么想法吗?谢谢。

Any ideas? Thanks.

编辑:

所以,如果我这样做:

def get_name(inst):
    client = boto3.client('ec2')
    response = client.describe_instances(InstanceIds = [inst[0].instance_id])
    foo = response['Reservations'][0]['Instances'][0]['NetworkInterfaces'][0]['Association']['PublicDnsName']
    return foo


foo = get_name(new_instance)
print foo

然后它将返回公共DNS。但是对我来说,为什么我需要做所有这些事情没有意义。

Then it will return the public DNS. But it doesn't make sense to me why I need to do all of this.

推荐答案

您返回的实例对象仅与响应混合在一起 create_instances 调用中的属性。由于DNS名称在实例达到运行状态之前不可用,因此 [1] ,它将不会立即显示。我想您从创建实例到调用describe实例之间的时间足以使微实例启动。

The Instance object you get back is only hydrated with the response attributes from the create_instances call. Since the DNS name is not available until the instance has reached the running state [1], it will not be immediately present. I imagine the time between you creating the instance and calling describe instances is long enough for the micro instance to start.

import boto3

ec2 = boto3.resource('ec2')
instances = ec2.create_instances(
    ImageId='ami-f0091d91',
    MinCount=1,
    MaxCount=1,
    InstanceType='t2.micro',
    KeyName='<KEY-NAME>',
    SecurityGroups=['<GROUP-NAME>'])
instance = instances[0]

# Wait for the instance to enter the running state
instance.wait_until_running()

# Reload the instance attributes
instance.load()
print(instance.public_dns_name)

这篇关于使用BOTO3检索EC2实例的公共DNS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆