Getting public dns instance of EC2 with BOTO3

I use ipython to understand Boto3 and interact with EC2 instances. Here is the code I use to create the 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 the instance of EC2 instance, and I can get the public DNS name, ip and other information from the AWS console. But, when I try to get public DNS using Boto by doing this:

 new_instance[0].public_dns_name 

Returns empty quotation marks. However, other instance details, such as:

 new_instance[0].instance_type 

Returns the correct information.

Any ideas? Thank you

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 makes no sense to me why I should do all this.

+12
python amazon-web-services dns boto3 aws-ec2
source share
2 answers

The returned Instance object only hydrates with the response attributes from the create_instances call. Since the DNS name is not available until the instance reaches state [1] , it will not be present immediately. I assume that the time between creating the instance and the call to describe the instances is long enough to start the micro-instance.

 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) 
+19
source share
 import boto3 import pandas as pd session = boto3.Session(profile_name='aws_dev') dev_ec2_client = session.client('ec2') response = dev_ec2_client.describe_instances() df = pd.DataFrame(columns=['InstanceId', 'InstanceType', 'PrivateIpAddress','PublicDnsName']) i = 0 for res in response['Reservations']: df.loc[i, 'InstanceId'] = res['Instances'][0]['InstanceId'] df.loc[i, 'InstanceType'] = res['Instances'][0]['InstanceType'] df.loc[i, 'PrivateIpAddress'] = res['Instances'][0]['PrivateIpAddress'] df.loc[i, 'PublicDnsName'] = res['Instances'][0]['PublicDnsName'] i += 1 print df Note: 1. Change this profile with your aws profile nameprofile_name='aws_dev 2. This code is working for python3 
0
source share