Search code examples
amazon-web-servicesaws-lambdawkhtmltopdfserverless-frameworkserverless

How to package executables in aws lambda function when using serverless framework?


I need to upload an executable file ( i.e. wkhtmltopdf to be exact) along with my function code in aws lambda. I'm using serverless framework. I tried different ways but the exe is not uploaded. The function works well when the code is zipped and uploaded via the aws dashboard.

Given below is the directory structure of the function that need to be uploaded

node_modules index.js wkhtmltopdf

This is my serverless.yml

service: consult-payment-api

frameworkVersion: ">=1.1.0 <2.0.0"

package:
  individually: true  

provider:
  name: aws
  region: us-west-2
  runtime: nodejs8.10
  stage: dev
  timeout: 300
  
functions:

  UserPackageCharge:
        handler:  payment/module/chargePackage.create
        package:
          include: 
            - packages/wkhtmltopdf
        events:
          - http:
              path: payment/module/package
              method: post
              cors: 
                origin: '*'
                headers:
                  - Content-Type
                  - X-Amz-Date
                  - Authorization
                  - X-Api-Key
                  - X-Amz-Security-Token
                  - X-Amz-User-Agent
                  - My-Custom-Header

This is my index.js (handler)

var wkhtmltopdf = require('wkhtmltopdf');
var MemoryStream = require('memorystream');

process.env['PATH'] = process.env['PATH'] + ':' + process.env['LAMBDA_TASK_ROOT'];

exports.handler = function(event, context) {
	var memStream = new MemoryStream();
	var html_utf8 = new Buffer(event.html_base64, 'base64').toString('utf8');
	wkhtmltopdf(html_utf8, event.options, function(code, signal) { context.done(null, { pdf_base64: memStream.read().toString('base64') }); }).pipe(memStream);	
};

But I still get the error 'Error: /bin/bash: wkhtmltopdf: command not found' How to get this working in serverless?


Solution

  • I did get a version working. The only issue I have (which I haven't worked through yet) is all the lambdas in that particular serverless.yml include the wkhtmlpdf - so they're all around 16 mb.

    Here's what I did:

    1. Created a package.json and added:

      "dependencies": {
      "wkhtmltopdf": "^0.3.4",
      "memorystream": "^0.3.1"
      },

    2. Ran ndm install

    3. Added WKhtmltopdf in the directory:
      enter image description here

    4. Added this in serverless.yml
      package:
      include:

      • wkhtmltopdf
    5. Added this in the lambda:
      var wkhtmltopdf = require('wkhtmltopdf');
      var MemoryStream = require('memorystream');