简体   繁体   English

使用 BOTO3 检索 EC2 实例的公共 DNS

[英]Retrieving public dns of EC2 instance with BOTO3

I'm using ipython to get an understanding of Boto3 and interacting with EC2 instances.我正在使用 ipython 来了解 Boto3 并与 EC2 实例进行交互。 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.这可以正常启动 EC2 实例,我可以从 AWS 控制台获取公共 DNS 名称、IP 和其他信息。 But, when I try to get the public DNS using Boto, by doing this:但是,当我尝试使用 Boto 获取公共 DNS 时,这样做:

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.然后它将返回公共 DNS。 But it doesn't make sense to me why I need to do all of this.但我不明白为什么我需要做所有这些。

The Instance object you get back is only hydrated with the response attributes from the create_instances call.您取回的Instance对象仅与来自create_instances调用的响应属性混合。 Since the DNS name is not available until the instance has reached the running state [1] , it will not be immediately present.由于 DNS 名称在实例达到运行状态[1]之前不可用,因此它不会立即出现。 I imagine the time between you creating the instance and calling describe instances is long enough for the micro instance to start.我想您创建实例和调用 describe 实例之间的时间足以让微实例启动。

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)

Here my wrapper:这是我的包装纸:

import boto3
from boto3.session import Session

def credentials():
    """Credentials:"""
    session = Session(aws_access_key_id= 'XXXXXXXXX',
                      aws_secret_access_key= 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
    ec2 = boto3.resource('ec2', region_name='us-east-2')
    return ec2

def get_public_dns(instance_id):
    """having the instance_id, gives you the public DNS"""
    ec2 = credentials()
    instance = ec2.Instance(instance_id)
    instancePublicDNS = instance.public_dns_name
    return instancePublicDNS

Then you just need to use your instance_id to get public dns of any of your actives ec2:然后你只需要使用你的 instance_id 来获取你的任何活动 ec2 的公共 dns:

dns = get_public_dns(instance_id)

Remember to change "region_name" to your zone and add your "aws_access_key_id" and "aws_secret_access_key"请记住将“region_name”更改为您的区域并添加您的“aws_access_key_id”和“aws_secret_access_key”

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 name profile_name='aws_dev'使用您的 AWS 配置文件名称更改此配置文件profile_name='aws_dev'
  2. This code is working for Python3此代码适用于 Python3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM