amazon-s3 - 如何从cloudformation/boto3访问S3 Bucket的名称?

标签 amazon-s3 aws-lambda aws-cloudformation boto3

我的团队希望在 cloudformation 模板中创建一个 S3 存储桶,而不为其分配存储桶名称(让 cloudformation 自行命名)。

当从我的 lambda 函数将文件放入 S3 存储桶时,有没有办法让我获取 S3 存储桶的名称,而无需手动查看 AWS 控制台并检查创建的名称?

最佳答案

使用无服务器应用程序模型 (SAM),您可以包含 environment variablesfunction 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/

相关文章:

node.js - expressjs文件下载内存泄漏

amazon-s3 - s3cmd:根据扩展名搜索文件并从存储桶中删除

python - Python-读取音频数据而不保存到文件

amazon-web-services - 在cloudformation中创建对象参数列表并将其传递给资源

amazon-web-services - AWS::ApiGateway::Method 在每次部署中都会被删除

yaml - 无服务器组件 yaml 中引用云形成堆栈

amazon-web-services - 使用 Namecheap DNS 的 Amazon S3 静态托管 - 如何正确路由非 www 前缀的 url

amazon-web-services - 如何在我的 Amazon S3 静态网站中获取查询字符串?

node.js - aws lambda 调用未在 POST 上填充正文

node.js - 如何在 AWS Lambda 中使用 Node.js 列出我的所有 Amazon EC2 实例?