如何访问云端 lambda@Edge 函数中的 S3 存储桶对象?

How access S3 bucket object in cloudfront lambda@Edge Function?

我有一个与我的云端分配关联的 Lambda 函数。

我想访问这个 egde@lambda 函数中的一些 S3 Bucket 对象。我没有找到一种方法来做到这一点,也不知道什么是最好的方法来做到这一点并且延迟最少。

我不想使用对存储桶的 http 调用来访问存储桶对象,因为它会导致云端响应出现一些延迟。

有谁知道我如何在边缘 lambda 函数中访问与我的云端分布相关的 S3 存储桶?

非常感谢。

您需要向与您的 lambda 关联的 IAM 角色授予权限。来自 AWS docs:

Each Lambda function has an IAM role (execution role) associated with it. You specify the IAM role when you create your Lambda function. Permissions you grant to this role determine what AWS Lambda can do when it assumes the role.

要从 lambda 读取和写入 S3 存储桶,您需要将 IAM 策略附加到与您的 lambda 关联的 IAM 角色。来自 AWS docs:

You manage access in AWS by creating policies and attaching them to IAM identities (users, groups of users, or roles) or AWS resources. A policy is an object in AWS that, when associated with an identity or resource, defines their permissions. AWS evaluates these policies when a principal entity (user or role) makes a request. Permissions in the policies determine whether the request is allowed or denied. Most policies are stored in AWS as JSON documents. AWS supports six types of policies: identity-based policies, resource-based policies, permissions boundaries, Organizations SCPs, ACLs, and session policies.

使用此 IAM 策略授予对与您的 lambda 关联的 IAM 角色的访问权限:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowS3Access",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::<account>:role/service-role/LAMBDA_ROLE_NAME"
            },
            "Action": [
                "s3:*"
            ],
            "Resource": [
                "arn:aws:s3:::<bucket-name>",
                "arn:aws:s3:::<bucket-name>/*"
            ]
        }
    ]
}

OBS: <account><bucket-name> 需要替换为正确的值。

之后,下面的代码应该可以工作了:

import aws from 'aws-sdk'

export default (event, context, callback) => {
  const s3 = new aws.S3()

  s3.getObject({
    Bucket: 'name-of-bucket',
    Key: 'my-key'
  }, (err, data) => {
    if (err) {
      callback(err)
      return
    }

    const objectData = data.Body.toString('utf-8')
    console.log(objectData)
  })
}