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" }),
  };
};
相关推荐
2501_9304724412 小时前
03_AWS迁移腾讯云_组件差异风险清单与工作量WBS
云计算·腾讯云·aws
Akiyama_Mio-Kon16 小时前
CVE-2026-85654 深度解读:DynamoDB MCP Server 如何把数据模型风险带到 CDK 部署宿主
aws·dynamodb·cdk·mcp·cve-2026-85654·lac·agent 安全
范桂飓2 天前
AWS Kiro Agent 架构解析
架构·云计算·aws
GreatVicent4 天前
AI Agent互操作标准化加速:A2A协议正式加入Linux基金会
linux·运维·人工智能·agent·aws·a2a
洋不写bug4 天前
绕过权限检查,访问修改私有属性,反射,枚举,lambda
java·枚举·lambda·反射
Akiyama_Mio-Kon5 天前
AWS AI 自动安全修复深度解读:从生成脚本到最小权限、双人审批与回滚审计闭环
aws·ai agent·security hub·guardduty·安全自动化·云安全治理
l1t9 天前
DeepSeek总结的DuckDB访谈:DuckDB的崛起、扩展与AWS收购
数据库·云计算·aws·duckdb
StarRocks_labs9 天前
StarRocks x Fluss x Paimon 湖流一体方案:构建秒级响应、湖流一体的实时数据引擎
starrocks·kafka·lambda·查询·paimon·fluss·湖流一体
snpgroupcn9 天前
云端共筑·数据跃迁——德勤×SNP×AWS联袂解读SAP ECC升级实战
云计算·aws
yyuuuzz9 天前
企业出海云服务器部署踩坑记录:从频繁超时到稳定运行的复盘
运维·服务器·网络·人工智能·aws