如何将通过堆栈导出的现有S3存储桶通过CloudFormation YAML导入到另一个堆栈中

问题描述 投票:0回答:1

类似于以下CloudformationYAML的工作方式。我最终得到了一个lambda函数,该函数会在S3存储桶中出现新对象时被触发。

Resources:
  myS3BucketResource:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Ref myS3BucketName
      AccessControl: Private
      VersioningConfiguration:
        Status: Enabled

LambdaFunction:
    Type: 'AWS::Serverless::Function'
    Properties:
      Handler: main.handler
      CodeUri:
        Bucket: !Ref CodeBucketName
        Key: !Ref CodeKey
      Role: !GetAtt
        - LambdaRole
        - Arn
      Runtime: nodejs12.x
      Timeout: !Ref LambdaTimeOut
      MemorySize: !Ref LambdaMemory
      FunctionName: !Sub '${Environment}-${FunctionName}'
      Events:
        S3Event:
          Type: S3
          Properties:
            Bucket: !Ref myS3BucketResource
            Events: 
              - 's3:ObjectCreated:Put'

但是,我需要做的是让lambda函数使用由另一个堆栈创建的现有S3存储桶。请注意,在上面,S3存储桶是由也创建lambda的同一CF模板创建的。

我似乎不能仅在S3Event的Bucket属性中引用S3存储桶名称,如下所示:

      Events:
        S3Event:
          Type: S3
          Properties:
            Bucket: !Ref myS3BucketName
            Events: 
              - 's3:ObjectCreated:Put'

因此,我想这是因为它至少必须基于上面可用的CF模板,而需要作为资源而不是字符串。

我读过有关Fn::ImportValue的内容,该内容用于导入已由另一堆栈导出的内容-我需要使用S3存储桶。但是我不知道如何在CF模板上指定它。

例如,在下面尝试过,但是没有用。没有Type: AWS::S3::Bucket行的情况下。

Resources:
  myS3BucketResource:
    Type: AWS::S3::Bucket
    Properties:
      Bucket:
        Fn::ImportValue: !Sub "${exportedS3Bucket}"

任何领导将不胜感激。如果有一种方法可以指定Bucket而不通过导入路径,那确实是最好的。

谢谢!

amazon-web-services amazon-s3 lambda yaml amazon-cloudformation
1个回答
0
投票

但是,我需要做的是让lambda函数使用由另一个堆栈创建的已经存在的S3存储桶。

假设对S3 bucket存储桶堆栈具有控制权,则可以将其导出以在其他堆栈中可见。您已经正确指出了这一点。

由于您尚未提供用于导出其引用的存储桶堆栈的代码,因此我只能将答案基于示例。在此示例中,不使用exportedBucket名称。

存储桶堆栈

Resources:
  myS3BucketResource:
    Type: AWS::S3::Bucket

Outputs:
  Name: 
    Value: !Ref myS3BucketResource
    Export:
      Name: exportedBucket  # <---- export bucket

使用lambda导入堆栈

LambdaFunction:
    Type: 'AWS::Serverless::Function'
    Properties:
      Handler: main.handler
      CodeUri:
        Bucket: !Ref CodeBucketName
        Key: !Ref CodeKey
      Role: !GetAtt
        - LambdaRole
        - Arn
      Runtime: nodejs12.x
      Timeout: !Ref LambdaTimeOut
      MemorySize: !Ref LambdaMemory
      FunctionName: !Sub '${Environment}-${FunctionName}'
      Events:
        S3Event:
          Type: S3
          Properties:
            Bucket: !ImportValue exportedBucket  # <---- import bucket
            Events: 
              - 's3:ObjectCreated:Put'
© www.soinside.com 2019 - 2024. All rights reserved.