Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving public dns of EC2 instance with BOTO3

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
    )

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

Returns the correct information.

Any ideas? Thanks.

EDIT:

So if I do:

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

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

like image 908
William Rudisill Avatar asked Jan 11 '16 18:01

William Rudisill


People also ask

What is boto3 client (' EC2 ')?

Client ¶ A low-level client representing Amazon Elastic Compute Cloud (EC2) Amazon Elastic Compute Cloud (Amazon EC2) provides secure and resizable computing capacity in the Amazon Web Services Cloud. Using Amazon EC2 eliminates the need to invest in hardware up front, so you can develop and deploy applications faster.

Can you lose public IP of EC2 instance?

You cannot manually associate or disassociate a public IP (IPv4) address from your instance. Instead, in certain cases, we release the public IP address from your instance, or assign it a new one: We release your instance's public IP address when it is stopped, hibernated, or terminated.


1 Answers

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)
like image 94
Jordon Phillips Avatar answered Oct 01 '22 20:10

Jordon Phillips