Python boto3 脚本无法获取实例标签值
Python boto3 script fails to get a instance tag value
我正在尝试获取实例的标签键 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
File "./test.py", line 9
autoinstinfo = ec2.describe_instances(InstanceIds=[liid], Filters=[{'Name':'tag:AutoScalingGroupName', 'Values':['%s']} % (AutoScalingGroupName)).get( 'Reservations', [] )
^
SyntaxError: invalid syntax
知道标签名为什么要用字符串格式?为什么不能执行以下操作?
ec2.describe_tags(Filters=[{'Name':'resource-id', 'Values':[liid]}, {'Name':'key', 'Values':['AutoScalingGroupName']}])['Tags'][0]['Value']
`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 帐户中所有实例的标签键。
我正在尝试获取实例的标签键 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
File "./test.py", line 9 autoinstinfo = ec2.describe_instances(InstanceIds=[liid], Filters=[{'Name':'tag:AutoScalingGroupName', 'Values':['%s']} % (AutoScalingGroupName)).get( 'Reservations', [] ) ^ SyntaxError: invalid syntax
知道标签名为什么要用字符串格式?为什么不能执行以下操作?
ec2.describe_tags(Filters=[{'Name':'resource-id', 'Values':[liid]}, {'Name':'key', 'Values':['AutoScalingGroupName']}])['Tags'][0]['Value']
`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 帐户中所有实例的标签键。