3
votes

Can a s3 bucket and triggered lambda be created in separate cloudformation templates. I want to keep long running resources stack separate from the likes of lambda which get updated quite frequently

When tried to create lambda separately it says that bucket defined in lambda event should be defined in same template and cannot be referenced.

GetFileMetadata:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      FunctionName: !Sub '${targetenv}-lambdaname'
      CodeUri: target-file-0.0.1-SNAPSHOT.jar
      Handler: LambdaFunctionHandler::handleRequest
      Runtime: java8
      Timeout: 30
      MemorySize: 512
      Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object
        Variables:
          STAGE: !Sub '${targetenv}'

      Events:
        S3Event:
          Type: S3
          Properties:
            Bucket:
              Ref: MyS3Bucket
            Events:
              - 's3:ObjectCreated:*'

  MyS3Bucket:
      Type: 'AWS::S3::Bucket'
      DependsOn: BucketPermission
      Properties:
          BucketName: !Sub 'bucketname-${targetenv}'
         # LifecycleConfiguration: 
          #  Rules:
           # - ExpirationInDays: 14
2

2 Answers

2
votes

This is not possible in SAM version 2016-10-31. Copied from the S3 event source type in the SAM documentation:

NOTE: To specify an S3 bucket as an event source for a Lambda function, both resources have to be declared in the same template. AWS SAM does not support specifying an existing bucket as an event source.

0
votes

The template is creating a bucket (MyS3Bucket).

Then, the serverless function is referencing it:

        Bucket:
          Ref: MyS3Bucket

If you want to refer to that bucket from another template, you can export the bucket name from the first stack:

Outputs:

  S3Bucket:
    Description: Bucket that was created
    Value: !Ref MyS3Bucket
    Export:
      Name: Stack1-Bucket

Then, import it into the second stack:

        Bucket:
            Fn::ImportValue:
              Stack1-Bucket

See: Exporting Stack Output Values - AWS CloudFormation