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" }),
  };
};
相关推荐
qqxhb1 天前
系统架构设计师备考第68天——大数据处理架构
大数据·hadoop·flink·spark·系统架构·lambda·kappa
网络精创大傻2 天前
在 AWS 上启动您的 AI 代理:Bedrock、Lambda 和 API 网关
人工智能·云计算·aws
weixin_307779132 天前
破解遗留数据集成难题:基于AWS Glue的无服务器ETL实践
开发语言·云原生·云计算·etl·aws
王道长服务器 | 亚马逊云3 天前
AWS + 发财CMS:高效采集站的新形态
服务器·网络·云计算·音视频·aws
赖small强3 天前
【ZeroRange WebRTC】在自有 AWS 环境实现与 Amazon KVS 等效的 WebRTC 安全方案(落地指南)
安全·webrtc·aws·访问控制·信令安全·媒体安全·监控与合规
AWS官方合作商3 天前
深入解析:利用EBS直接API实现增量快照与精细化数据管理(AWS)
运维·云计算·aws
AWS官方合作商4 天前
AWS EC2实例重启后SSH/SFTP连接失败的全面排查指南
云计算·ssh·aws
AWS官方合作商4 天前
AWS Lambda的安全之道:S3静态加密与运行时完整性检查的双重保障
安全·云计算·aws
王道长服务器 | 亚马逊云5 天前
AWS + 苹果CMS:影视站建站的高效组合方案
服务器·数据库·搜索引擎·设计模式·云计算·aws
可观测性用观测云5 天前
AWS CloudFront 可观测最佳实践
aws