Update AWS Lambda Function automatically / 25 Oct 2019 / Author: Haim Ari

    Estimated read time: 2 minutes

    Updating a new version for your AWS Lambda function is not very fun…

    The main reason for making this gitlab pipeline was to avoid the need to use the Browser, then Logging in to the AWS console, zipping your code and uploading it manually.

    It is possible to do that from Cli, but I prefer to simply being able to commit –> push code and let the gitlab pipeline to do the rest.

    This is a very minimal gitlab ci which updates your python code: you can easily adjust it to your needs.

    The main part of deploying your changes is here.

    .gitlab-ci.yml
    image: python:3.6.1
    
    stages:
      - deploy
    
    deploy:
      stage: deploy
      script:
        - cd Aws_Lambda
        - pip install -r requirements.txt -t .
        - pip install -r requirements.txt
        - zip -r /tmp/artifact.zip *
        - python ../lambda_deploy.py # run the deployment script
    

    You can simply pip install boto3 instead of using requirements.

    lambda_deploy.py

    As you can see, the “deploy” stage installs some dependencies, and then calls the python script Bellow in order too deploy the artifact

    (python zip file of your code)

    from __future__ import print_function
    import boto3
    import sys
    import os
    from botocore.exceptions import ClientError
    
    """ This function runs gitlab pipeline to update AWS Lambda function """
    
    AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID']
    AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']
    AWS_DEFAULT_REGION = os.environ['AWS_DEFAULT_REGION']
    
    
    def publish_new_version(artifact):
        """
        Publishes new version of the AWS Lambda Function
        """
        try:
            client = boto3.client('lambda')
        except ClientError as err:
            print("Failed to create boto3 client.\n" + str(err))
            return False
    
        try:
            response = client.update_function_code(
                FunctionName='your_function_name',
                ZipFile=open(artifact, 'rb').read(),
                Publish=True
            )
            return response
        except ClientError as err:
            print("Failed to update function code.\n" + str(err))
            return False
        except IOError as err:
            print("Failed to access " + artifact + ".\n" + str(err))
            return False
    
    
    def main():
        if not publish_new_version('/tmp/artifact.zip'):
            sys.exit(1)
    
    
    if __name__ == "__main__":
        main()
    

    That’s it.

    Each time the gitlab pipeline runs (you can change that according to your needs) the zip is created, Then that artifact is deployed to your lambda function.