编写 Boto3 过滤器以使用自定义标签名称的正确方法是什么? [英] What is the correct ways to write Boto3 filters to use customise tag name?

查看:20
本文介绍了编写 Boto3 过滤器以使用自定义标签名称的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试列出不同标签键的标签值上的实例例如>一个标签键 - 环境,另一个标签键 - 角色.我的代码如下:

I am trying to list the instances on tag values of different tag keys For eg> one tag key - Environment, other tag key - Role. My code is given below :

import argparse
import boto3

AWS_ACCESS_KEY_ID = '<Access Key>'
AWS_SECRET_ACCESS_KEY = '<Secret Key>'

def get_ec2_instances(Env,Role):
    ec2 = boto3.client("ec2", region)
    reservations = ec2.describe_instances(Filters={"tag:environment" :   Env, "tag:role" : Role})
    for reservation in reservations["Reservations"] :
        for instance in reservation["Instances"]:
             print  "%s" % (instance.tags['Name'])

if  __name__ == '__main__':

    regions = ['us-east-1','us-west-1','us-west-2','eu-west-1','sa-east-1',
               'ap-southeast-1','ap-southeast-2','ap-northeast-1']
    parser = argparse.ArgumentParser()
    parser.add_argument('Env', default="environment", help='value for   tag:environment');
    parser.add_argument('Role', default="role", help='value for tag:role');
    args = parser.parse_args()

    for region in regions: get_ec2_instances(args.Env, args.Role)

运行此脚本后:python script.py arg1 arg2

After running this script : python script.py arg1 arg2

我收到以下错误

Traceback (most recent call last):
  File "script.py", line 27, in <module>
    for region in regions: get_ec2_instances(args.Env, args.Role)
  File "script.py", line 10, in get_ec2_instances
    reservations = ec2.describe_instances(Filters={"tag:environment" :  Env, "tag:role" : Role})
  File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line 258, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line 524, in _make_api_call
    api_params, operation_model, context=request_context)
  File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line 577, in _convert_to_request_dict
    api_params, operation_model)
  File "/usr/local/lib/python2.7/dist-packages/botocore/validate.py", line 270, in serialize_to_request
    raise ParamValidationError(report=report.generate_report())
botocore.exceptions.ParamValidationError: Parameter validation failed:
Invalid type for parameter Filters, value: {'tag:role': 'arg1', 'tag:environment': 'arg2'}, type: <type 'dict'>, valid types: <type 'list'>, <type 'tuple'>

推荐答案

这看起来很熟悉,我是不是在某个地方为某人修改了这个 ;-) .实际上,我编写的代码很匆忙,没有经过适当的测试(而且我也懒得修改 % 字符串格式并将其替换为 str.format() ).事实上,AWS 中没有正确记录使用 Filters 参数.

This looks familiar, did I modify this for somebody somewhere ;-) . Actually the code I wrote is in rush and not tested properly (And I don't bother to amend the % string formating and replace it with str.format() ) . In fact,using Filters parameter is not properly documented in AWS.

请参阅 Russell Ballestrini 博客 使用 Boto3 过滤 AWS 资源了解有关正确 boto 过滤器方法的更多信息.

Please refer to Russell Ballestrini blog Filtering AWS resources with Boto3 to learn more about correct boto Filters method.

  1. 过滤器接受列表值,标签内的信息应该是字典.因此 [{}]
  2. Boto3 文档对于如何使用指定标签名称非常含糊.当他们说您可以使用 tag:key 时,没有示例会令人困惑.很多人只会做 [{"tag:keyname","Values": [""] }] 而它不起作用.(实际上,我假设开发人员知道过滤器的工作原理是原始代码,所以我只是修改了结构).
  3. 实际上,您必须明确指定名称"和值"对.所以指定标签名称的正确方法是[{"Name" :"tag:keyname", "Values":[""] }].这很棘手.
  1. Filters accept list value, and info inside the tag should be dict. thus [{}]
  2. Boto3 documentation is pretty ambiguous on how to use specify the tag name. It is confusing without examples when they say you may use tag:key. So many people will just do [{"tag:keyname","Values": [""] }] and it doesn't work. (Actually the origin code I assume the developer know how the filters works, so I just amend the structure only).
  3. Actually, You MUST explicitly specify "Name" and "Values" pair. So the correct way to specify tag name is [{"Name" :"tag:keyname", "Values":[""] }]. It is tricky.

如果你想在你的例子中使用过滤器的正确格式

So the correct way of formatting a filters if you want to use for your example

filters = [{'Name':'tag:environment', 'Values':[Env]},
           {'Name':'tag:role', 'Values':[Role]}
          ]

(更新)并且为了确保 argparse 接受字符串值,您只需强制参数接受字符串值

(Update) And to make sure argparse take up string value, you just enforce the argument to take string values

parser.add_argument('Env', type=str, default="environment",
                    help='value for   tag:environment');
parser.add_argument('Role', type=str,default="role",
                    help='value for tag:role');

这篇关于编写 Boto3 过滤器以使用自定义标签名称的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆