Titulum
Titulum

Reputation: 11446

How to create Lambda using CloudFormation and only deploy zip file after?

I have the following CloudFormation template:

AWSTemplateFormatVersion: '2010-09-09'
Resources:
   HostingBucket:
      Type: AWS::S3::Bucket
      Properties:
         BucketName: "my-hosting-bucket"
   LambdaExecutionRole:
      Type: AWS::IAM::Role
      Properties:
         AssumeRolePolicyDocument:
            Version: '2012-10-17'
            Statement:
               - Effect: Allow
                 Principal:
                  Service: lambda.amazonaws.com
                 Action: sts:AssumeRole
         ManagedPolicyArns:
            - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
   MyFunction:
      Type: AWS::Lambda::Function
      Properties:
         Handler: index.handler
         Runtime: nodejs12.x
         Role: !GetAtt 'LambdaExecutionRole.Arn'
         Timeout: 300
         Code:
            S3Bucket: !Ref 'HostingBucket'
            S3Key: !Sub 'lambda/backend.zip'

But while deploying this I get the following error:

Resource handler returned message: "Error occurred while GetObject. S3 Error Code: NoSuchKey. S3 Error Message: The specified key does not exist. (Service: Lambda, Status Code: 400, Request ID: SOME-REQUEST-ID)"

Now I understand why the error occurs: my lambda is trying to get the deployed code, but it's not there yet because the S3 is created in the same stack. Probably I will need the following steps:

  1. Create S3 bucket (via CloudFormation)
  2. Deploy lambda code to created S3 bucket
  3. Create lambda (via CloudFormation)

How can I deploy this CloudFormation template before deploying my Lambda handler to S3? I'd like to use the following flow:

  1. Create S3 bucket and lambda (via CloudFormation)
  2. Deploy lambda code to created S3 bucket
  3. Have lambda pick up the newest code (which happens automatically iirc)

Upvotes: 0

Views: 1439

Answers (2)

Miguel Angel
Miguel Angel

Reputation: 26

So far, the only way to do that is that you split the stacks one for lambda deployment bucket and another one for all lambda resources.

Upvotes: 0

Tim Schill
Tim Schill

Reputation: 91

You would typically deploy your artifact into S3 during build time in a pipeline.

Upvotes: 0

Related Questions