【问题标题】:Python boto3 script fails to get a instance tag valuePython boto3 脚本获取实例​​标签值失败
【发布时间】:2017-02-26 19:29:16
【问题描述】:

我正在尝试获取实例的标记键 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: 无效语法

【问题讨论】:

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


    【解决方案1】:

    既然知道标签名,为什么还要使用字符串格式?为什么以下不能工作?

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

    【讨论】:

    • 我只是得到空字典? []
    • `# python3.4 ./test.py []
    • 我没有发现任何错误,但是我得到了这个运行实例的所有信息。只需要“AutoScalingGroupName”值。我在打印声明中缺少什么?
    • @bobby 你太复杂了。如果您只想要标签值,请使用我刚刚更新的那个。如果你懂python,那么如果不存在这样的标签,你就会知道如何处理。
    • 感谢您的指正,效果很好,我应该使用ec2.describe_tags
    【解决方案2】:
    `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 帐户中所有实例的标签键。

    【讨论】:

    • 以上脚本将为您提供 aws 帐户中所有实例的标签键
    猜你喜欢
    • 2017-05-17
    • 2017-02-23
    • 1970-01-01
    • 2021-08-30
    • 2018-11-22
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    相关资源
    最近更新 更多