如何在 sam 模板中引用 s3 存储桶名称的环境变量值?

How to refer the environment variable value for s3 bucket name in sam template?

我正在尝试通过引用定义的环境变量来构建 s3 事件应用程序。

下面是我所指的模板


AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  CreateThumbnail:
    Type: AWS::Serverless::Function
    Properties:
      Handler: handler
      Runtime: runtime
      Timeout: 60
      Policies: AWSLambdaExecute
      Environment:
        Variables:
          BUCKET_NAME: !Sub "${S3}"

      Events:
        CreateThumbnailEvent:
          Type: S3
          Properties:
            Bucket: ""How can refer the s3 bucket form the environment here"
            Events: s3:ObjectCreated:*

  

我实际上需要从 'Environment variable' 中引用 'BUCKET NAME' 并且还需要从同一个 s3 添加事件触发器。

有人可以帮忙吗?

谢谢

有两种选择,

或者您已经在同一模板中定义了 S3 存储桶,然后您可以使用逻辑 CFN ID 引用它:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  S3Bucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: my-bucket-name
  CreateThumbnail:
    Type: AWS::Serverless::Function
    Properties:
      Handler: handler
      Runtime: runtime
      Timeout: 60
      Policies: AWSLambdaExecute
      Environment:
        Variables:
          BUCKET_NAME: !Ref S3Bucket
      Events:
        CreateThumbnailEvent:
          Type: S3
          Properties:
            Bucket: !Ref S3Bucket
            Events: s3:ObjectCreated:*

或者您没有在同一个模板中定义它,在这种情况下,您必须在部署期间将其作为参数传递给堆栈,如下所示:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Parameters:
  S3Bucket:
    Description: Name of the S3 Bucket
    Type: String
Resources:
  CreateThumbnail:
    Type: AWS::Serverless::Function
    Properties:
      Handler: handler
      Runtime: runtime
      Timeout: 60
      Policies: AWSLambdaExecute
      Environment:
        Variables:
          BUCKET_NAME: !Ref S3Bucket
      Events:
        CreateThumbnailEvent:
          Type: S3
          Properties:
            Bucket: !Ref S3Bucket
            Events: s3:ObjectCreated:*