How to create a new version of a Lambda function using CloudFormation?

后端 未结 11 655
清歌不尽
清歌不尽 2020-12-08 03:44

I\'m trying to create a new version of a Lambda function using CloudFormation.

I want to have multiple versions of the same Lambda function so that I can (a) point a

11条回答
  •  温柔的废话
    2020-12-08 04:42

    This is a bit of a hack, and depends on using gitlab-ci (or something similar), but I find passing the commit hash into a cloudformation template (via the template's parameters) very useful.

    (It's a bit like @Jerry 's answer, but using the commit hash.)

    In this case you could do something like:

    Have a parameter in your template for the commit hash, e.g.:

    AWSTemplateFormatVersion: '2010-09-09'
    Description: Template for Lambda Sample.
    Parameters:
      ciCommitSha:
        Type: String
      s3Bucket:
        Type: String
      ...
    

    You can then reference this in the lambda resource, like this:

      CFNLambda:
        Type: AWS::Lambda::Function
        Properties:
          FunctionName: cfn_trigger_fn
          Description: lambda which gets triggered by cloudformation
          Runtime: python3.7
          Code:
            S3Bucket: !Ref s3Bucket
            S3Key: !Join [ ".", [ !Ref ciCommitSha, "zip"]]
          Handler: function.handler
          ...
    

    Your ci pipeline then needs to look something like (assuming you call your cloudformation template stack-template.yaml):

    variables:
      REGION: us-east-1
      S3_BUCKET_NAME: my-bucket
    
    stages:
     - build
     - push
     - deploy
    
    build-package:
      stage: build
      script:
        - some code to produce a deployment package called function.zip
      artifacts:
        name: deployment_package
        paths:
          - function.zip
    
    
    push-code:
      stage: push
      script:
        - aws s3 cp function.zip s3://$S3_BUCKET_NAME/$CI_COMMIT_SHA.zip
    
    deploy-trigger-stack:
      stage: deploy
      script: 
          - aws cloudformation deploy
                --template-file stack-template.yaml
                --stack-name my-stack
                --region $REGION
                --no-fail-on-empty-changeset
                --capabilities CAPABILITY_NAMED_IAM
                --parameter-overrides
                ciCommitSha=$CI_COMMIT_SHA
                s3Bucket=$S3_BUCKET_NAME
    

    You can use this technique for triggering cfn-init on EC2 metadata as well..

提交回复
热议问题