AWS学习笔记之Lambda执行权限引发的思考

最近在网上看到一道关于AWS Lambda的题,十分有意思:

复制代码
A developer has an application that uses an AWS Lambda function to upload files to Amazon S3 and needs the required permissions to
perform the task. The developer already has an IAM user with valid IAM credentials required for Amazon S3.
What should a solutions architect do to grant the permissions?
A. Add required IAM permissions in the resource policy of the Lambda function.
B. Create a signed request using the existing IAM credentials in the Lambda function.
C. Create a new IAM user and use the existing IAM credentials in the Lambda function.
D. Create an IAM execution role with the required permissions and attach the IAM role to the Lambda function.

仔细想了想,这是在问如何让Lambda有可以上传文件到S3上的权限。而IAM user和相关凭证都是配置好的。

而Lambda是需要用某种IIAM role来执行的,且这个Role是需要有S3的操作权限来上传文件的。看完四个选项,只有D是正确的。而A是用来迷惑人的,IAM permissions是加在Role上的,并不是直接配置在Lambda上。

再进一步再想,这个配置在AWS中该如何编写呢?

配置如下:

复制代码
{
  "Effect": "Allow",
  "Action": "s3:PutObject",
  "Resource": "arn:aws:s3:::your-bucket-name/*"
}

回想一下项目中也会用serverless语法来设置IAM role有s3的一些权限,殊途同归罢了,具体serverless.yml的内容如下所示:

复制代码
service: upload-service

provider:
  name: aws
  runtime: nodejs18.x
  region: ap-northeast-1
  iamRoleStatements:
    - Effect: Allow
      Action:
        - s3:PutObject
      Resource:
        - arn:aws:s3:::test-bucket/*
  
functions:
  uploader:
    handler: handler.uploadFile
    events:
      - http:
          path: upload
          method: post

plugins:
  - serverless-offline

随后,编写对应的lambda代码,假设还是用nodejs实现(假设保存在名为handler.js的文件中):

复制代码
onst AWS = require('aws-sdk');
const s3 = new AWS.S3();

module.exports.uploadFile = async (event) => {
  const content = Buffer.from("test for lambda");
  const bucketName = "test-bucket";

  await s3.putObject({
    Bucket: bucketName,
    Key: "example.txt",
    Body: content,
  }).promise();

  return {
    statusCode: 200,
    body: JSON.stringify({ message: "Uploaded successfully" }),
  };
};
相关推荐
翼龙云_cloud14 小时前
亚马逊云渠道商:如何快速开始使用Amazon RDS?
运维·服务器·云计算·aws
weixin_3077791320 小时前
基于AWS Global Accelerator和ECS Fargate的最小化延迟与快速故障转移架构
容器·云计算·aws
济南java开发,求内推21 小时前
AWS 对接
云计算·aws
AWS官方合作商1 天前
无缝升级,保障业务连续性:深入解析Amazon RDS单可用区转多可用区
云计算·aws
AWS官方合作商2 天前
AWS GPU实例深度解析:G系列与P系列如何选择?
云计算·aws
北辰浮光3 天前
[Amplify]项目aws-amplfiy服务旧版本升级v6经验分享
云计算·aws
艾莉丝努力练剑4 天前
【C++:C++11】C++11新特性深度解析:从可变参数模板到Lambda表达式
c++·stl·c++11·lambda·可变模版参数
syounger6 天前
奔驰全球 IT 加速转型:SAP × AWS × Agentic AI 如何重塑企业核心系统
人工智能·云计算·aws
翼龙云_cloud6 天前
亚马逊云渠道商:AWS Shield和传统防火墙怎么选?
运维·服务器·云计算·aws
翼龙云_cloud6 天前
亚马逊云渠道商:如何利用AWS工具进行日常安全运维?
运维·安全·云计算·aws