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

时间:2018-08-22 07:47:38

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

我正在尝试检索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'

2 个答案:

答案 0 :(得分:0)

您将两个想法混为一谈。

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

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

使用

ec2 = boto3.client('ec2')

然后

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

第二个实例从ec2 资源(而不是boto3 ec2客户端)查找ec2实例。

答案 1 :(得分:0)

这是一个有效的代码,以防将来有人将其发布到这里。它将在打开所有实例后关闭它们,然后打印它们的所有实例的公共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()