Home > Back-end >  how to have multiple lambda function in single git repo and create a CI/CD pipeline for the same
how to have multiple lambda function in single git repo and create a CI/CD pipeline for the same

Time:12-07

I have a solution but in that, I've to make an individual deply.yml for each lambda, (Like if have 10 lambdas then I've to make 10 deploy.yml for each lambda). I was wondering if this job can be done with single deploy.yml (I also tried serverless but it didn't work).

CodePudding user response:

In serverless, you can achieve as below with single serverless.yaml

service: my-service
package:
  individually: true
  patterns:
    - '!src/excluded-by-default-for-all-functions.json'
functions:
  hello:
    handler: handler.hello
    package:
      # We're including this file so it will be in the final package of this function only
      patterns:
        - function1/path/somefile.json #some path for function1
        - excluded-by-default.json # you can add ignored file in this function alone
  world:
    handler: handler.world
    package:
      patterns:
        - '!some-file.js' #Not including this file
        - 'function2/path/another-file.json' #Including this file
        - '!path123/**' #Don't include any file in this path

CodePudding user response:

You can use AWS SAM for this. You would have a template.yml file like this:

Transform: AWS::Serverless-2016-10-31

Parameters:
  Function1Hash:
    Type: String
  Function2Hash:
    Type: String

Resources:
  Function1:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: path/to/my/code
      Role: !GetAtt MyRole.Arn
      Runtime: myruntime
      Handler: lambda_function.handler
      AutoPublishCodeSha256: !Ref Function1Hash

  Function2:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: path/to/my/code
      Role: !GetAtt MyRole.Arn
      Runtime: myruntime
      Handler: lambda_function.handler
      AutoPublishCodeSha256: !Ref Function2Hash

You generate a hash for each lambda. This way, if the lambda code changes, so will the hash. Then you inject these hashes as parameters to your templates, and only the lambda with new code will be updates, garanteed by the AutoPublishCodeSha256 attribute. Something like this in your deploy.yml (untested):

hash_func_1=$(md5sum lambda1.py | awk '{print $1}')
hash_func_2=$(md5sum lambda2.py | awk '{print $1}')

sam deploy --stack-name my-lambdas -t template.yml --parameter-overrides Function1=$hash_func_1 Function2=$hash_func_2
  • Related