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" }),
  };
};
相关推荐
tech讯息13 小时前
商业化内容生产适用企业级视频生成模型云平台推荐|从模型生成至审核分发全链路 AWS 选型方案
人工智能·音视频·aws
知无不研2 天前
lambda表达式的使用(3)
开发语言·c++·lambda
ShineWinsu3 天前
对于C++:C++11中lambda、function、bind的解析
c++·面试·笔试·开发·lambda·bind·function
测试运维日常笔记4 天前
AWS EKS 集群部署与清理手顺
云计算·aws
故乡dee云4 天前
AWS 产品太多不会选?按“网站、数据库、文件、日志”4 类需求快速匹配
数据库·云计算·aws
翼龙云_cloud6 天前
亚马逊云代理商:VPC网络ACL和安全组配置实践 从网络层到实例层的双重防护
运维·网络·安全·云计算·aws
Freed&11 天前
阿里云 OSS 至 AWS S3 跨云迁移实施指南
阿里云·云计算·aws
故乡dee云12 天前
AWS CloudFront 使用教程:CDN 加速功能和网站部署优化
云计算·aws
国际云,接待17 天前
AWS RDS 备份与 PITR 恢复演练:从保留期、恢复命令到应用切换验证
运维·云计算·aws·灾难恢复·数据库备份·rds
国际云,接待18 天前
AWS账单防爆雷实战:Budgets、Cost Anomaly Detection与预算动作联动
人工智能·aws·twitter·finops·云成本·budgets