使用 JmesPath 过滤 CloudTrail 日志

Using JmesPath to filter CloudTrail logs

我正在开发一个 boto 脚本以使用 JmesPath 过滤掉 cloudtrail。
JmesPath 应该将输出作为存储桶的名称。我不确定什么是正确的语法。提前致谢。

logs = cloudtrail.create_trail(
  Name='GoodTrail',
  S3BucketName='goodbucket3',
)
print(logs)
        
path = jmespath.search('logs',{'S3BucketName': ''}})
print(path)

这是print(logs)给出的:

{
    "Name": "GoodTrail",
    "S3BucketName": "goodbucket3",
    "IncludeGlobalServiceEvents": true,
    "IsMultiRegionTrail": false,
    "TrailARN": "arn:aws:cloudtrail:us-east-1:XXXXXXXXXXX:trail/GoodTrail",
    "LogFileValidationEnabled": false,
    "IsOrganizationTrail": false,
    "ResponseMetadata": {
        "RequestId": "520fdfae-02ea-4695-857c-c47c7bcb00dd",
        "HTTPStatusCode": 200,
        "HTTPHeaders": {
            "x-amzn-requestid": "520fdfae-02ea-4695-857c-c47c7bcb00dd",
            "content-type": "application/x-amz-json-1.1",
            "content-length": "242",
            "date": "Fri, 18 Dec 2020 15:48:26 GMT"
        },
        "RetryAttempts": 0
    }
}

这一行的三大问题:

path = jmespath.search('logs',{'S3BucketName': ''}})
  1. 当使用 JMESPath search 函数时,您必须将表达式作为第一个参数,将 JSON 文档作为第二个参数,此时您在这里做相反的事情。
    search(<jmespath expr>, <JSON document>) -> <return value>
    
    来源:https://jmespath.org/specification.html#jmespath-specification
    所以你应该有:
    path = jmespath.search('some-search-experssion', some_variable)
    
  2. 您正在将字符串 'logs' 传递给 search 函数,而不是包含 JSON 文档本身的变量 logs,因此它应该是
    path = jmespath.search('some-search-experssion', logs)
    
  3. 要搜索像您这样的简单对象,您只需要立即引用对象的键即可,因此您的搜索表达式应该只是:S3BucketName
    path = jmespath.search('S3BucketName', logs)
    

所以,所有的脚本 test.py:

import jmespath

logs = {
    "Name": "GoodTrail",
    "S3BucketName": "goodbucket3",
    "IncludeGlobalServiceEvents": True,
    "IsMultiRegionTrail": False,
    "TrailARN": "arn:aws:cloudtrail:us-east-1:562922379100:trail/GoodTrail",
    "LogFileValidationEnabled": False,
    "IsOrganizationTrail": False,
    "ResponseMetadata": {
        "RequestId": "520fdfae-02ea-4695-857c-c47c7bcb00dd",
        "HTTPStatusCode": 200,
        "HTTPHeaders": {
            "x-amzn-requestid": "520fdfae-02ea-4695-857c-c47c7bcb00dd",
            "content-type": "application/x-amz-json-1.1",
            "content-length": "242",
            "date": "Fri, 18 Dec 2020 15:48:26 GMT"
        },
        "RetryAttempts": 0
    }
}

#print(logs)

path = jmespath.search('S3BucketName', logs)
print(path)

给出:

$ python3 test.py 
goodbucket3