Python boto3脚本无法获取实例标记值

时间:2016-10-17 17:55:22

标签: amazon-web-services amazon-ec2 boto3

我正在尝试获取实例的Tag键AutoScalingGroupName的值。 Python boto3脚本因语法错误而失败。

这是我的示例脚本。

#!/bin/python3.4
import requests
import boto3
import botocore.session
import urllib.request

ec2 = boto3.client('ec2', region_name='us-west-1', aws_access_key_id='****************', aws_secret_access_key='****************************')
liid = urllib.request.urlopen('http://169.254.169.254/latest/meta-data/instance-id').read().decode()
autoinstinfo = ec2.describe_instances(InstanceIds=[liid], Filters=[{'Name':'tag:AutoScalingGroupName', 'Values':['%s']} % ['AutoScalingGroupName']).get( 'Reservations', [] )
print(autoinstinfo)

发生此错误消息失败。

  

python3.4 ./test.py

     

文件“./test.py”,第9行   autoinstinfo = ec2.describe_instances(InstanceIds = [liid],Filters = [{'Name':'tag:AutoScalingGroupName','Values':['%s']}%(AutoScalingGroupName))。get('Reservations',[ ])                           ^      SyntaxError:语法无效

2 个答案:

答案 0 :(得分:1)

为什么在知道标签名称时想要使用字符串格式?为什么以下工作无法完成?

ec2.describe_tags(Filters=[{'Name':'resource-id', 'Values':[liid]}, {'Name':'key', 'Values':['AutoScalingGroupName']}])['Tags'][0]['Value']

答案 1 :(得分:1)

`import boto3

ec2 = boto3.resource('ec2')
client = boto3.client('ec2')

response = client.describe_instances()

for r in response['Reservations']:
    for instance in r['Instances']:
        Tags = instance['Tags'][0]['Key']
        print(Tags)`

上面的脚本将为您提供aws帐户中所有实例的标记键。