使用Lambda捕获Athena查询执行细节



在CloudWatch下,我创建了一个规则来捕获Athena查询状态更改事件,该事件将(1)将日志写入日志组(2)触发Lambda函数,该函数将捕获Athena查询执行细节并将其管道传输到s3桶。第2点失败了,因为没有Athena查询执行细节通过管道传递到s3桶。下面是我使用的Lambda函数:

import json
import boto3
from botocore.config import Config
my_config = Config(
region_name = '<my_region>')

print('Loading function')
def lambda_handler(event, context):
print("Received event: " + json.dumps(event))
print("QuertID: " + event['id'])

#get query statistics
client = boto3.client('athena', config=my_config)
queries = client.get_query_execution( QueryExecutionId=event['detail']['QueryExecutionId'])
del queries['QueryExecution']['Status']
#saving the query statistics to s3
s3 = boto3.resource('s3')
object = s3.Object('<s3_bucket_path>','query_statistics_json/' + event['detail']['QueryExecutionId'])
object.put(Body=str(queries['QueryExecution']))
return 0

我使用这个AWS文档作为参考:https://docs.aws.amazon.com/athena/latest/ug/control-limits.html

正文类型为二进制数据

object.put(Body=some binary data)

也许你可以将str(queries['QueryExecution']写入lambda的/tmp目录下的txt文件并上传。

content="String content to write to a new S3 file"
s3.Object('my-bucket-name', '/tmp/newfile.txt').put(Body=content)

这只是一个缩进的问题,在第11行之后,所有的都应该缩进…