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" }),
  };
};
相关推荐
JiL 奥14 小时前
Ubuntu系统安装AWS SAM
云计算·aws
xianyinsuifeng1 天前
RAG + Code Analysis 的标准路线
数据仓库·自动化·云计算·原型模式·aws
万博智云OneProCloud2 天前
CloudEndure 退出中国市场之后,AWS 容灾该走向哪里?
云计算·aws
翼龙云_cloud2 天前
亚马逊云渠道商:如何从本地环境安全访问AWS云数据库RDS?
数据库·云计算·aws
索荣荣2 天前
Java定时任务与Kubernetes CronJob、AWS EventBridge的集成方案指南
java·开发语言·kubernetes·aws
亚林瓜子2 天前
AWS Glue任务中使用一个dynamic frame数据过滤另外一个dynamic frame数据
java·python·sql·spark·aws·df·py
代码N年归来仍是新手村成员3 天前
DynamoDB 速通
数据库·nosql·aws
i建模4 天前
在Windows系统上通过SSH访问远程AWS主机
windows·ssh·aws
Lim小刘4 天前
云边协同实战:基于 AWS IoT Greengrass 的智能工厂视觉检测方案深度拆解
物联网·视觉检测·aws
因_果_律4 天前
无需Mac Mini!使用ClawdBot(Moltbot)& AWS EC2的搭建你的24小时AI搭子
云计算·aws·亚马逊云科技