简体   繁体   English

如何在云端 lambda@Edge Function 中访问 S3 存储桶 object?

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

I have a Lambda function which is associated to my cloudfront distribution.我有一个 Lambda function 与我的云端分配相关联。

I want access some S3 Bucket objects in this egde@lambda function. I did not find a way to do that and do not know what is the best way to do this and have the minimum delay.我想访问这个 egde@lambda function 中的一些 S3 Bucket 对象。我没有找到这样做的方法,也不知道什么是最好的方法,并且延迟最少。

I do not want to access bucket objects using http calls to the bucket because it will give some delay in cloudfront response.我不想使用对存储桶的 http 调用来访问存储桶对象,因为它会给云端响应带来一些延迟。

Anyone know how I can access my S3 Bucket related to my cloudfront distribution in edge lambda function?任何人都知道我如何访问与边缘 lambda function 中的云端分布相关的 S3 存储桶?

Many Thanks.非常感谢。

You need to grant permissions to the IAM role associated with your lambda. 您需要向与lambda关联的IAM角色授予权限。 From AWS docs : AWS文档中

Each Lambda function has an IAM role (execution role) associated with it. 每个Lambda函数都有一个与之关联的IAM角色(执行角色)。 You specify the IAM role when you create your Lambda function. 创建Lambda函数时,可以指定IAM角色。 Permissions you grant to this role determine what AWS Lambda can do when it assumes the role. 您授予此角色的权限确定了AWS Lambda在担任该角色时可以做什么。

To read and write an S3 bucket from the lambda, you will need to attach an IAM policy to the IAM role associated with your lambda. 要从Lambda读取和写入S3存储桶,您需要将IAM策略附加到与Lambda相关联的IAM角色。 From AWS docs : AWS文档中

You manage access in AWS by creating policies and attaching them to IAM identities (users, groups of users, or roles) or AWS resources. 您可以通过创建策略并将其附加到IAM身份(用户,用户组或角色)或AWS资源来管理AWS中的访问。 A policy is an object in AWS that, when associated with an identity or resource, defines their permissions. 策略是AWS中的一个对象,当与身份或资源关联时,将定义其权限。 AWS evaluates these policies when a principal entity (user or role) makes a request. 当主体实体(用户或角色)发出请求时,AWS会评估这些策略。 Permissions in the policies determine whether the request is allowed or denied. 策略中的权限确定请求是被允许还是被拒绝。 Most policies are stored in AWS as JSON documents. 大多数策略作为JSON文档存储在AWS中。 AWS supports six types of policies: identity-based policies, resource-based policies, permissions boundaries, Organizations SCPs, ACLs, and session policies. AWS支持六种类型的策略:基于身份的策略,基于资源的策略,权限边界,组织SCP,ACL和会话策略。

Use this IAM policy to grant access to the IAM role associated with your lambda: 使用此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 : the <account> and <bucket-name> need to be replaced with the correct values. OBS<account><bucket-name>需要替换为正确的值。

After that, the following code should work: 之后,以下代码应该工作:

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)
  })
}

You can create an origin access identity, associate it with your CF distro, then update the bucker resource policy (Ie the bucket permissions) to grant the proper privileges to the origin access identity.您可以创建一个原始访问身份,将其与您的 CF 发行版相关联,然后更新 bucker 资源策略(即存储桶权限)以向原始访问身份授予适当的权限。 Below is Serverless Stack code which is an extension of AWS CDK constructs:下面是无服务器堆栈代码,它是 AWS CDK 构造的扩展:

// Create origin access identity
const originAccessIdentity = new OriginAccessIdentity(stack, 'myOriginAccessIdentity', {
    comment: 'My Origin Access Identify'
  })

// Associate the origin access identity created above with my CF distro
const dist = new Distribution(stack, 'myCloudFrontDistribution', {
  ...
  defaultBehavior: {
      originAccessIdentity
  })
  ...
})

and the resource policy on the S3 bucket looks like this: S3 存储桶上的资源策略如下所示:

{
    "Version": "2008-10-17",
    "Statement": [
        {
            "Sid": "My SID",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E2R76GGGJFJ9SS"
            },
            "Action": "s3:GetObject",
            "Resource": [
                "arn:aws:s3:::my-bucket/resized/*"
            ]
        }
    ]
}

Note the "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E2R76GGGJFJ9SS" .注意"AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E2R76GGGJFJ9SS" The E2R76GGGJFJ9SS is the ID of the origin access identity created above, which can be accessed like so: E2R76GGGJFJ9SS就是上面创建的源访问身份的ID,可以这样访问:

originAccessIdentity.originAccessIdentityId

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过 S3 和 Lambda@Edge 从部署在 Cloudfront 上的 Nextjs API 抓取 Request URL - How to grab Request URL from Nextjs API deployed on Cloudfront through S3 and Lambda@Edge 如何为cloudfront 添加IAM 权限以关联lambda@edge? - How to add IAM permission to cloudfront in order to associate lambda@edge? AWS CloudFront Lambda@Edge 部署 - AWS CloudFront Lambda@Edge deployment 带有 Lambda@Edge 的 CloudFront 未被触发 - CloudFront with Lambda@Edge not getting triggenred Lambda@Edge 未登录云端请求 - Lambda@Edge not logging on cloudfront request 修复 Cloudfront 403 Access Denied 请求错误时使用 Lambda@Edge 漂亮的 URL - Fix Cloudfront 403 Access Denied request errors when using Lambda@Edge for pretty URLs 在 NodeJS 中使用 Lambda@Edge 对 CloudFront 进行基本 HTTP 身份验证 - Basic HTTP Authentication for CloudFront with Lambda@Edge in NodeJS Cloudfront 和 Lambda@Edge 的 Twitter 和 LinkedIn 元标记问题 - Issue with Twitter and LinkedIn meta tags with Cloudfront & Lambda@Edge CloudFront 中的 AWS Lambda@Edge 502 LambdaValidationError 用于重定向 - AWS Lambda@Edge 502 LambdaValidationError in CloudFront for redirect Lambda@Edge function 与 Nodejs 返回 502 错误 Lambda function 在标头 object 中返回了无效条目 - Lambda@Edge function with Nodejs return 502 ERROR The Lambda function returned an invalid entry in the headers object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM