使用Lambda函数运行AWS Athena查询

问题描述 投票:1回答:2

我在AWS Athena上创建了一个表,可以在该表上运行任何查询而没有任何错误:

select * from mytestdb.test

表有三列,customer_Id, product_Id, price

我尝试创建一个lambda函数,使用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。

amazon-web-services aws-lambda
2个回答
2
投票

正如我在评论中提到的那样,您的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/*"
    } 
  ]
}

0
投票

汗的想法对我有用。

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

AWS Policies

© www.soinside.com 2019 - 2024. All rights reserved.