无法将 AWS Lambda 连接到 Elastic Search。收到 403 错误

Unable to connect AWS Lambda to Elastic Search. Getting a 403 error

我正在尝试按照教程中的说明将流数据从 Amazon Kinesis Data Streams 加载到 Amazon ES:https://docs.aws.amazon.com/elasticsearch-service/latest/developerguide/es-aws-integrations.html#es-aws-integrations-kinesis

如教程中所述,我的 lambda 函数是:

import base64
import boto3
import json
import requests
from requests_aws4auth import AWS4Auth

region = 'us-east-1'
service = 'es'
credentials = boto3.Session().get_credentials()
awsauth = AWS4Auth(credentials.access_key, credentials.secret_key, region, service, session_token=credentials.token)

host = '' # the ES domain has been specified here
index = 'lambda-kine-index'
type = 'lambda-kine-type'
url = host + '/' + index + '/' + type + '/'

headers = { "Content-Type": "application/json" }

def handler(event, context):
    count = 0
    for record in event['Records']:
        id = record['eventID']
        timestamp = record['kinesis']['approximateArrivalTimestamp']
        
        # Kinesis data is base64-encoded, so decode here
        message = base64.b64decode(record['kinesis']['data'])
        
        # Create the JSON document
        document = { "id": id, "timestamp": timestamp, "message": message }
        # Index the document
        r = requests.put(url + id, auth=awsauth, json=document, headers=headers)
        count += 1
    return 'Processed ' + str(count) + ' items.'

此外,如教程中所述,IAM 角色是:


{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "es:ESHttpPost",
        "es:ESHttpPut",
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents",
        "kinesis:GetShardIterator",
        "kinesis:GetRecords",
        "kinesis:DescribeStream",
        "kinesis:ListStreams"
      ],
      "Resource": "*"
    }
  ]
}

信任关系是:


{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

这样做之后,我 运行 lambda 得到的响应是:

<Response [403]>

感谢任何解决此问题的帮助。

确保您的凭据有效。您可以使用 aws-cli 验证这一点。请参阅文档 here.

凭证仅在您使用 IAM 用户时适用,但此处并非如此,因为这是一个 Lambda 函数,它需要一个 IAM 角色。

您可能启用了细粒度访问控制,但它不能很好地与域策略配合使用。

阅读更多内容 here 并注意突出显示的部分重新使用/IAM 混合且无法正常工作。

对于收到 403 且上述解决方案不适用的人...

如果您使用精细权限,则需要将您的 lambda 执行角色添加为后端角色(在 kibana 中配置)。

在 Kibana -> 安全/角色

  • 将您的角色添加到“all_access”(或任何对您的用例有意义的角色)