【问题标题】:Error in retrieving public dns name of ec2 instance检索 ec2 实例的公共 dns 名称时出错
【发布时间】:2019-01-28 10:24:37
【问题描述】:

我正在尝试检索 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 名称。

我现在根据以下建议更改了代码

import sys
import boto3


instance_id = "i-03e7f6391a0f523ee"
action = 'ON'

ec2 = boto3.client('ec2')
#instance = ec2.resource('ec2').instance(instance_id)
if action == 'ON':
   response = ec2.start_instances(InstanceIds=[instance_id], DryRun=False)
else:
    response = ec2.stop_instances(InstanceIds=[instance_id], DryRun=False)
print(response)



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)

但现在我得到错误

in get_name
    response = client.describe_instances(InstanceIds = [inst[0].instance_id])
AttributeError: 'str' object has no attribute 'instance_id'

【问题讨论】:

    标签: python python-3.x amazon-web-services amazon-ec2 boto3


    【解决方案1】:

    您将两个想法合二为一。

    boto3.client 创建一个对象,您可以通过该对象查找 ec2 等资源。

    一旦你有了资源,你就可以开始操作它了。

    使用

    ec2 = boto3.client('ec2')
    

    然后

    instance = ec2.resource('ec2').instance(instance_id)
    

    第二个从 ec2 resource 而非 boto3 ec2 客户端查找您的 ec2 实例。

    【讨论】:

    • 我不清楚 boto3.client 和 ec2.resurce() 之间的区别
    • 我再次收到错误instance = ec2.resource('ec2').instance(instance_id) File "E:\installation2\python3\lib\site-packages\botocore\client.py", line 555, in __getattr__ self.__class__.__name__, item) AttributeError: 'EC2' object has no attribute 'resource'
    • 我已经更改了代码并提到了新的问题仍然存在错误。
    【解决方案2】:

    这是一个工作代码,以防将来有人点击这里我发布它。这将在打开所有实例然后关闭它们后打印所有实例的公共 DNS 名称。

      import boto3
    from pprint import pprint
    
    
    ec2=boto3.client('ec2')
    response=ec2.describe_instances()
    print (response)
    
    instancelist = []
    for reservation in (response["Reservations"]):
        for instance in reservation["Instances"]:
            instancelist.append(instance["InstanceId"])
    print (instancelist)
    
    
    action ='ON'
    if action == 'ON':
       response = ec2.start_instances(InstanceIds=instancelist, DryRun=False)
    
    ec2client = boto3.resource('ec2')
    #response = ec2client.describe_instances()
    
    
    instances = ec2client.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running','stopped']}])
    ids = []
    
    for instance in instances:
        print(instance.id, instance.instance_type)
        ids.append(instance.id)
        resp=ec2.describe_network_interfaces();
        print ("printing pub dns name")
        print(resp['NetworkInterfaces'][0]['Association']['PublicDnsName'])
    
    
    ec2client.instances.filter(InstanceIds=ids).stop()
    

    【讨论】:

      猜你喜欢
      • 2021-04-25
      • 2016-04-16
      • 2013-08-29
      • 2014-10-17
      • 2014-01-23
      • 2015-03-23
      • 2015-10-12
      • 2014-12-29
      • 2014-05-13
      相关资源
      最近更新 更多