使用Lambda函数运行AWS Athena的查询
问题描述:
我在AWS Athena上创建了一个表,可以在该表上运行任何查询而不会出现任何错误:
I created a table on AWS Athena on which I can run any query without any error:
select * from mytestdb.test
该表具有三列customer_Id, product_Id, price
.
我尝试创建一个lambda函数,该函数使用boto3为我运行相同的查询:
I tried to create a lambda function that run the same query for me using boto3:
import time
import boto3
DATABASE = 'mytestdb'
TABLE = 'test'
output='s3://mybucketons3/'
COLUMN = 'Customer_Id'
def lambda_handler(event, context):
keyword = 'xyz12345'
query = "SELECT * FROM %s.%s where %s = '%s';" % (DATABASE, TABLE, COLUMN, keyword)
client = boto3.client('athena')
# Execution
response = client.start_query_execution(
QueryString=query,
QueryExecutionContext={
'Database': DATABASE
},
ResultConfiguration={
'OutputLocation': output,
}
)
return
但是我遇到以下错误:
Response:
{
"errorMessage": "An error occurred (AccessDeniedException) when calling the StartQueryExecution operation: User: arn:aws:sts::076088932150:assumed-role/Test/QueryTest is not authorized to perform: athena:StartQueryExecution on resource: arn:aws:athena:us-west-2:076088932150:workgroup/primary",
"errorType": "ClientError",
这似乎是访问问题,但是我不确定为什么,因为我同时拥有同一个帐户的lambda和athena db.
It seems sort of access issue however I am not sure why because I have both lambda and athena db with the same account.
答
正如我在评论中提到的那样,您的Lambda角色应包含允许策略与Athena服务进行交互.我还为您的S3存储桶添加了完整权限.示例:
As I've mentioned in the comment, your Lambda role should contain Allow policy to interact with Athena service. I've also added full permissions for your S3 bucket. Example:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Stmt1547414166585",
"Action": [
"athena:StartQueryExecution"
],
"Effect": "Allow",
"Resource": "*"
},
{
"Sid": "Stmt1547414166586",
"Action": [
"s3:*"
],
"Effect": "Allow",
"Resource": "arn:aws:s3:::your-bucket-name/*"
}
]
}