Jenkinsfile: AWS Lambda deployment from S3 bucket

Reading Time: 2 minutes

AWS Lambda limits the amount of compute and storage resources that you can use to run and store functions. The deployment package size is 50 MB (zipped). Here is the solution how to beat it. Take a look at this blog for S3 solution as well.  

Problem

aws lambda update-function-code \
  --function-name ${DEV_LAMBDA_FUNCTION} \
  --region eu-west-2 \
  --s3-bucket name_of_s3_bucket \
  --s3-key deployment.zip

Assuming that you created a zip file called “deployment.zip”, the above command results in the following error:

An error occurred (RequestEntityTooLargeException) when calling the UpdateFunctionCode operation: Request must be smaller than 69905067 bytes for the UpdateFunctionCode operation

Solution

First, we need to create an AWS S3 bucket in one of the AWS Regions to store your data in.  Then, we can use following code in Jenkisnfile to upload zip file to S3 bucket and update the AWS Lambda.

// Create deployment zip file
stage('Zip up') {
   steps {
      ansiColor('xterm'){
        unstash 'build-artefacts'
        echo "NODE_NAME = ${env.NODE_NAME}"
        script {
           def file = '/workspace/syildirim/deployment.zip'
           if (fileExists(file)) {
              echo 'Remove and update zip file'
              sh 'rm -rf deployment.zip' 
              zip archive: true, dir: '', glob: '', zipFile: 
              'deployment.zip' 
           } else {
              echo 'Update zip file'
              zip archive: true, dir: '', glob: '', zipFile: 
              'deployment.zip' 
           }
       }
    }
}

// Upload zip file to S3 bucket and update AWS Lambda
stage('Deploy to lambda function') {
  steps {
    withCredentials([[
     $class: 'AmazonWebServicesCredentialsBinding',
     credentialsId: 'aws-credentials',
     accessKeyVariable: 'AWS_ACCESS_KEY_ID',
     secretKeyVariable: 'AWS_SECRET_ACCESS_KEY'
    ]]) {
      sh '''
        #!/bin/sh
        set +x
        AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID} 
        AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY} 
        export AWS_DEFAULT_REGION=${AWS_REGION}

        # upload zip file to S3 bucket
        aws s3 cp deployment.zip s3://zip-bucket/deployment.zip

        # update lambda using S3 bucket
        aws lambda update-function-code \
          --function-name ${DEV_LAMBDA_FUNCTION} \
          --region eu-west-2 \
          --s3-bucket zip-bucket \
          --s3-key deployment.zip
        '''
     }
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *