使用Lambda函数来运行AWS Athena的查询

7
我在AWS Athena上创建了一张表格,可以运行任何查询而不会出错:
select * from mytestdb.test
表格有三列,分别是customer_Id, product_Id, price

我尝试使用boto3创建一个lambda函数来运行相同的查询:

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数据库。


您的Lambda角色是否具有athena:StartQueryExecution允许策略? - A.Khan
对于 Lambda 角色,我选择“选择现有角色”,唯一可用的现有角色是“service-role/Test”,我是否需要创建任何自定义角色? - Amir
是的,您的 Lambda 角色应该包含允许与其交互的所有 AWS 服务的策略。我将在答案中提供一个示例策略。 - A.Khan
如果我想在Lambda中使用Athena运行多个查询,应该怎么做? - akash sharma
3个回答

7
如我在评论中所提到的,您的Lambda角色应包含与Athena服务交互的允许策略。我还为您的S3存储桶添加了完全权限。示例:
{
  "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/*"
    } 
  ]
}

谢谢。我收到了一个错误信息:“单个策略中的语句ID(SID)必须是唯一的。” 我应该将SIDs更改为两个唯一的ID吗? - Amir
如果我想在Athena中运行多个查询,使用Lambda,我该怎么做? - akash sharma

0

A.Khan的想法对我很有用。

使用AWS控制台编辑Lambda的IAM角色,以拥有AmazonAthenaFullAccess和AmazonS3FullAccess策略。

AWS Policies


1
这对我起作用了,但不是立即生效的。等待几分钟后,注销并使用我的用户重新登录,错误最终消失了。 - Nick K9

0

提供/添加服务的完全访问权限并不是最佳实践。您可以尝试限制访问仅限于Lambda需要执行的操作。 尝试使用特定权限重新部署IAM角色,并在成功部署后重新附加到Lambda函数。 您的Lambda肯定会正常工作。如果添加所需权限后仍然出现访问被拒绝的情况,则从您的帐户中提出AWS支持票证。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接