我的团队希望在 cloudformation 模板中创建一个 S3 存储桶,而不为其分配存储桶名称(让 cloudformation 自行命名)。
当从我的 lambda 函数将文件放入 S3 存储桶时,有没有办法让我获取 S3 存储桶的名称,而无需手动查看 AWS 控制台并检查创建的名称?
最佳答案
使用无服务器应用程序模型 (SAM),您可以包含 environment variables与 function properties
AWSTemplateFormatVersion: '2010-09-09'
Description: "Demo"
Transform: 'AWS::Serverless-2016-10-31'
Resources:
MyLambdaFunction:
Type: 'AWS::Serverless::Function'
Properties:
Runtime: nodejs10.x
Handler: index.handler
CodeUri: ./src
Policies:
- Version: '2012-10-17'
Statement:
- Action:
- s3:PutObject
Effect: 'Allow'
Resource: !Sub ${MyS3Bucket.Arn}/*
Environment:
Variables:
BUCKET_NAME: !Ref MyS3Bucket
MyS3Bucket:
Type: 'AWS::S3::Bucket'
然后你的函数就可以使用node.js中的process.env.BUCKET_NAME
来访问环境变量。在 python我认为您会使用os.environ['BUCKET_NAME']
const aws = require('aws-sdk');
const s3 = new aws.S3();
exports.handler = async (event) => {
const params = {
Body: 'The Body',
Bucket: process.env.BUCKET_NAME,
Key: 'abc123',
}
return s3.putObject(params).promise();
}
我认为这适用于任何不使用 SAM 转换的 CloudFormation 模板。
关于amazon-s3 - 如何从cloudformation/boto3访问S3 Bucket的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46900597/