首页 > 解决方案 > 无法使用 boto3 创建 ResourceGroup:查询格式无效

问题描述

我正在尝试使用以下 boto3 片段创建资源组:

kwargs = {
    'Name': 'cluster.foo.io',
    'Description': 'AWS resources assigned to the foo cluster.',
    'ResourceQuery': {
        'Type': 'TAG_FILTERS_1_0',
        'Query': '[{"Key": "foo.io/cluster", "Values": ["cluster.foo.io"]}]',
    },
    'Tags': {
        'foo.io/cluster': 'cluster.foo.io'
    }
}

client = boto3.client("resource-groups")
resp = client.create_group(**kwargs)

但我收到以下错误:

File "/Users/benjamin/.pyenv/versions/3.7.3/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/client.py", line 357, in _api_call
    return self._make_api_call(operation_name, kwargs)
File "/Users/benjamin/.pyenv/versions/3.7.3/Python.framework/Versions/3.7/lib/python3.7/site-packages/botocore/client.py", line 661, in _make_api_call
    raise error_class(parsed_response, operation_name)
botocore.errorfactory.BadRequestException: An error occurred (BadRequestException) 
    when calling the CreateGroup operation: Query not valid: 
    Query format not valid: check JSON syntax

我一直将查询与文档中的示例进行比较,但要么我没有看到差异,要么我在左侧字段中很差。我什至使用json如下模块:

resp = self.resource_client.create_group(
    Name='cluster.foo.io',
    Description="AWS resources assigned to the foo cluster",
    ResourceQuery={
        "Type": "TAG_FILTERS_1_0",
        "Query": json.dumps([{"Key": "foo.io/cluster", "Values": ["cluster.foo.io"]}]),
    },
    Tags={
        "foo.io/cluster": "cluster.foo.io",
    },
)

任何帮助,将不胜感激!

标签: python-3.xamazon-web-servicesboto3

解决方案


查询参数缺少 ResourceTypeFilters 和 TagFilters。因此,ResourceQuery 应该如下所示:

'ResourceQuery': {
    'Type': 'TAG_FILTERS_1_0',
    'Query': "{\"ResourceTypeFilters\": [\"AWS::AllSupported\"], \"TagFilters\": [{\"Key\": \"foo.io/cluster\", \"Values\": [\"cluster.foo.io\"]}]}"
}

因此,您的代码应替换如下(要替换的主要部分是 ResourceQuery:

query = {
    "ResourceTypeFilters": ["AWS::AllSupported"],
    "TagFilters": [{
        "Key": "foo.io/cluster",
        "Values": ["cluster.foo.io"]
    }]
}
resource_query = {
    'Type': 'TAG_FILTERS_1_0',
    'Query': json.dumps(query)
}
kwargs = {
    'Name': 'cluster.foo.io',
    'Description': 'AWS resources assigned to the foo cluster.',
    'ResourceQuery': resource_query,
    'Tags': {
        'foo.io/cluster': 'cluster.foo.io'
    }
}
client = boto3.client("resource-groups")
resp = client.create_group(**kwargs)

我参考了此处显示的示例 CLI 。


推荐阅读