检索 ec2 实例的公共 dns 名称时出错

我正在尝试检索 ec2 实例的公共 dns 名称。


这是我的python3脚本。


import sys

import boto3

from botocore.exceptions import ClientError


instance_id = "i-03e7f6391a0f523ee"

action = 'ON'


ec2 = boto3.client('ec2')



if action == 'ON':

    # Do a dryrun first to verify permissions

    try:

        ec2.start_instances(InstanceIds=[instance_id], DryRun=True)

    except ClientError as e:

        if 'DryRunOperation' not in str(e):

            raise


    # Dry run succeeded, run start_instances without dryrun

    try:

        response = ec2.start_instances(InstanceIds=[instance_id], DryRun=False)

        print(response)

    except ClientError as e:

        print(e)

else:

    # Do a dryrun first to verify permissions

    try:

        ec2.stop_instances(InstanceIds=[instance_id], DryRun=True)

    except ClientError as e:

        if 'DryRunOperation' not in str(e):

            raise


    # Dry run succeeded, call stop_instances without dryrun

    try:

        response = ec2.stop_instances(InstanceIds=[instance_id], DryRun=False)

        print(response)

    except ClientError as e:

        print(e)


instance = ec2.Instance('i-1234567890123456')

while instance.state['Name'] not in ('running', 'stopped'):

        sleep(5)

        print("the instance is initializing")


#pubdns=instance.PublicDnsName


#print ("public dns name"+pubdns)

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(instance_id)

print (foo)

如果我使用


ec2 = boto3.client('ec2')

在上面的代码中,出现以下错误:


AttributeError:“ EC2”对象没有属性“ Instance”


如果我用


ec2 = boto3.resource('ec2')

然后我得到这个错误:


AttributeError:“ ec2.ServiceResource”对象没有属性“ start_instances”


我想要做的是能够连接到 ec2 实例并检索其 publicdns 名称。

但是现在我得到了错误


in get_name

    response = client.describe_instances(InstanceIds = [inst[0].instance_id])

AttributeError: 'str' object has no attribute 'instance_id'


牛魔王的故事
浏览 139回答 2
2回答

神不在的星期二

您将两个想法混为一谈。boto3.client 创建一个对象,您可以通过该对象查找 ec2 等资源。一旦有了资源,就可以开始对其进行操作。用ec2 = boto3.client('ec2')然后instance = ec2.resource('ec2').instance(instance_id)第二个从 ec2资源而不是 boto3 ec2 客户端查找您的 ec2 实例。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python