Retrieving public dns of EC2 instance with BOTO3

孤者浪人 提交于 2019-12-04 00:58:54

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)
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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!