我正在嘗試檢索 ec2 實(shí)例的公共 dns 名稱。這是我的python3腳本。import sysimport boto3from botocore.exceptions import ClientErrorinstance_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 foofoo = get_name(instance_id)print (foo)如果我使用ec2 = boto3.client('ec2')在上面的代碼中,出現(xiàn)以下錯(cuò)誤:AttributeError:“ EC2”對(duì)象沒(méi)有屬性“ Instance”如果我用ec2 = boto3.resource('ec2')然后我得到這個(gè)錯(cuò)誤:AttributeError:“ ec2.ServiceResource”對(duì)象沒(méi)有屬性“ start_instances”我想要做的是能夠連接到 ec2 實(shí)例并檢索其 publicdns 名稱。但是現(xiàn)在我得到了錯(cuò)誤in get_name response = client.describe_instances(InstanceIds = [inst[0].instance_id])AttributeError: 'str' object has no attribute 'instance_id'
2 回答

神不在的星期二
TA貢獻(xiàn)1963條經(jīng)驗(yàn) 獲得超6個(gè)贊
您將兩個(gè)想法混為一談。
boto3.client 創(chuàng)建一個(gè)對(duì)象,您可以通過(guò)該對(duì)象查找 ec2 等資源。
一旦有了資源,就可以開始對(duì)其進(jìn)行操作。
用
ec2 = boto3.client('ec2')
然后
instance = ec2.resource('ec2').instance(instance_id)
第二個(gè)從 ec2資源而不是 boto3 ec2 客戶端查找您的 ec2 實(shí)例。
添加回答
舉報(bào)
0/150
提交
取消