Giter Site home page Giter Site logo

node-lambda's Introduction

If you found this useful, consider also checking out dotenv-vault. Thank you! 😇

node-lambda

node-lambda

Command line tool to locally run and deploy your node.js application to Amazon Lambda.

Node CI NPM version

$ node-lambda run

Installation

With npx:

$ npx node-lambda@latest [COMMAND]

Globally installed:

$ npm install -g node-lambda

Example App

Example apps make it easy to get up and running

Usage

There are 4 available commands.

$ npx node-lambda@latest setup
$ npx node-lambda@latest run
$ npx node-lambda@latest package
$ npx node-lambda@latest deploy

Commands

setup

Initializes the event.json, context.json, .env, deploy.env files, and event_sources.json files. event.json is where you mock your event. context.json is where you can add additional mock data to the context passed to your lambda function. .env is where you place your deployment configuration. deploy.env has the same format as .env, but is used for holding any environment/config variables that you need to be deployed with your code to Lambda but you don't want in version control (e.g. DB connection info). event_sources.json is used to set the event source of the Lambda function (Not all event sources available in Lambda are supported).

$ npx node-lambda@latest setup --help

Usage: setup [options]

Sets up the .env file.


Options:
  -h, --help                        output usage information
  -j, --eventFile [event.json]      Event JSON File
  -x, --contextFile [context.json]  Context JSON File

After running setup, it's a good idea to gitignore the generated event.json and .env files, as well as .lambda.

$ echo -e ".env\ndeploy.env\nevent.json\n.lambda" >> .gitignore
Deploy env variables
PACKAGE_MANAGER            // (default: 'npm')
AWS_ENVIRONMENT            // (default: '')
AWS_ENDPOINT               // (default: '')
CONFIG_FILE                // (default: '')
EVENT_SOURCE_FILE          // (default: '')
EXCLUDE_GLOBS              // (default: '')
AWS_ACCESS_KEY_ID          // (default: not set!)
AWS_SECRET_ACCESS_KEY      // (default: not set!)
AWS_PROFILE =              // (default: '')
AWS_SESSION_TOKEN =        // (default: '')
AWS_REGION =               // (default: 'us-east-1,us-west-2,eu-west-1')
AWS_FUNCTION_NAME          // (default: package.json.name or 'UnnamedFunction')
AWS_HANDLER                // (default: 'index.handler')
AWS_ROLE_ARN || AWS_ROLE   // (default: 'missing')
AWS_MEMORY_SIZE            // (default: 128)
AWS_TIMEOUT                // (default: 60)
AWS_RUN_TIMEOUT            // (default: 3)
AWS_ARCHITECTURE           // (default: 'x86_64')
AWS_DESCRIPTION            // (default: package.json.description or '')
AWS_RUNTIME                // (default: 'nodejs16.x')
AWS_PUBLISH                // (default: false)
AWS_FUNCTION_VERSION       // (default: '')
AWS_VPC_SUBNETS            // (default: '')
AWS_VPC_SECURITY_GROUPS    // (default: '')
AWS_TRACING_CONFIG         // (default: '')
AWS_LAYERS                 // (default: '')
AWS_LOGS_RETENTION_IN_DAYS // (default: '')
EVENT_FILE                 // (default: 'event.json')
PACKAGE_DIRECTORY          // (default: not set)
CONTEXT_FILE               // (default: 'context.json')
PREBUILT_DIRECTORY         // (default: '')
SRC_DIRECTORY              // (default: '')
DEPLOY_TIMEOUT             // (default: '120000')
DOCKER_IMAGE               // (default: '')
DEPLOY_ZIPFILE             // (default: '')
DEPLOY_USE_S3              // (default: false)
IMAGE_URI                  // (default: '')
AWS_DLQ_TARGET_ARN         // (default: not set)
AWS_TAGS                   // (default: '')

run

Runs your Amazon Lambda index.js file locally. Passes event.json data to the Amazon Lambda event object.

$ npx node-lambda@latest run --help
Usage: node-lambda run|execute [options]

Run your Amazon Lambda application locally

Options:
  -H, --handler [AWS_HANDLER]                                 Lambda Handler {index.handler} (default: "index.handler")
  -j, --eventFile [EVENT_FILE]                                Event JSON File (default: "event.json")
  -u, --runtime [AWS_RUNTIME]                                 Lambda Runtime (default: "nodejs16.x")
  -t, --timeout [AWS_RUN_TIMEOUT]                             Lambda Timeout (default: 3)
  -f, --configFile [CONFIG_FILE]                              Path to file holding secret environment variables (e.g. "deploy.env") (default: "")
  -x, --contextFile [CONTEXT_FILE]                            Context JSON File (default: "context.json")
  -M, --enableRunMultipleEvents [ENABLE_RUN_MULTIPLE_EVENTS]  Enable run multiple events (default: true)
  -y, --proxy [PROXY]                                         Proxy server (default: "")
  --apiGateway                                                Convert to API Gateway events (default: false)
  -h, --help                                                  display help for command

package

Bundles your application into a local zip file.

$ npx node-lambda@latest package --help
Usage: node-lambda package|zip [options]

Create zipped package for Amazon Lambda deployment

Options:
  --packageManager [PACKAGE_MANAGER]            Package manager used to install dependencies (default: "npm", options: "npm", "yarn")
  -A, --packageDirectory [PACKAGE_DIRECTORY]    Local Package Directory
  -I, --dockerImage [DOCKER_IMAGE]              Docker image for npm ci (default: "")
  -n, --functionName [AWS_FUNCTION_NAME]        Lambda FunctionName (default: "node-lambda")
  -H, --handler [AWS_HANDLER]                   Lambda Handler {index.handler} (default: "index.handler")
  -e, --environment [AWS_ENVIRONMENT]           Choose environment {dev, staging, production} (default: "")
  -x, --excludeGlobs [EXCLUDE_GLOBS]            Space-separated glob pattern(s) for additional exclude files (e.g.
                                                "event.json dotenv.sample") (default: "")
  -D, --prebuiltDirectory [PREBUILT_DIRECTORY]  Prebuilt directory (default: "")
  -m, --keepNodeModules [KEEP_NODE_MODULES]     Keep the current node_modules directory. (default: false)
  -v, --dockerVolumes [DOCKER_VOLUMES]          Additional docker volumes to mount. Each volume definition has to be
                                                separated by a space (e.g. "$HOME/.gitconfig:/etc/gitconfig
                                                $HOME/.ssh:/root/.ssh") (default: "")
  --no-optionalDependencies                     Run `npm install` with `--no-optional`
  -h, --help                                    display help for command

deploy

Bundles and deploys your application up to Amazon Lambda.

$ npx node-lambda@latest deploy --help
Usage: node-lambda deploy [options]

Deploy your application to Amazon Lambda

Options:
  --packageManager [PACKAGE_MANAGER]                    Package manager used to install dependencies (default: "npm", options: "npm", "yarn")
  -e, --environment [AWS_ENVIRONMENT]                   Choose environment {dev, staging, production} (default: "")
  -E, --endpoint [AWS_ENDPOINT]                         Choose endpoint (e.g. localstack, "http://127.0.0.1:4574") (default: "")
  -a, --accessKey [AWS_ACCESS_KEY_ID]                   AWS Access Key
  -s, --secretKey [AWS_SECRET_ACCESS_KEY]               AWS Secret Key
  -P, --profile [AWS_PROFILE]                           AWS Profile (default: "")
  -k, --sessionToken [AWS_SESSION_TOKEN]                AWS Session Token (default: "")
  -r, --region [AWS_REGION]                             AWS Region (default: "us-east-1,us-west-2,eu-west-1")
  -n, --functionName [AWS_FUNCTION_NAME]                Lambda FunctionName (default: "node-lambda")
  -H, --handler [AWS_HANDLER]                           Lambda Handler {index.handler} (default: "index.handler")
  -o, --role [AWS_ROLE]                                 Amazon Role ARN (default: "missing")
  -m, --memorySize [AWS_MEMORY_SIZE]                    Lambda Memory Size (default: 128)
  -t, --timeout [AWS_TIMEOUT]                           Lambda Timeout (default: 60)
  --architecture [AWS_ARCHITECTURE]                     The instruction set architecture that the function supports.  (x86_64|arm64) (default: "x86_64")
  -d, --description [AWS_DESCRIPTION]                   Lambda Description (default: "Command line tool for locally running and remotely deploying your node.js applications to Amazon Lambda.")
  -u, --runtime [AWS_RUNTIME]                           Lambda Runtime (default: "nodejs16.x")
  -p, --publish [AWS_PUBLISH]                           Lambda Publish (default: false)
  -L, --lambdaVersion [AWS_FUNCTION_VERSION]            Lambda Function Version (default: "")
  -b, --vpcSubnets [AWS_VPC_SUBNETS]                    Lambda Function VPC Subnet IDs (comma delimited) (default: "")
  -g, --vpcSecurityGroups [AWS_VPC_SECURITY_GROUPS]     Lambda VPC Security Group IDs (comma delimited) (default: "")
  -K, --kmsKeyArn [AWS_KMS_KEY_ARN]                     Lambda KMS Key ARN (default: "")
  -Q, --deadLetterConfigTargetArn [AWS_DLQ_TARGET_ARN]  Lambda DLQ resource
  -c, --tracingConfig [AWS_TRACING_CONFIG]              Lambda tracing settings (default: "")
  -l, --layers [AWS_LAYERS]                             Lambda Layers settings (e.g. "ARN1,ARN2[,..])" (default: "")
  -R, --retentionInDays [AWS_LOGS_RETENTION_IN_DAYS]    CloudWatchLogs retentionInDays settings (default: "")
  -G, --sourceDirectory [SRC_DIRECTORY]                 Path to lambda source Directory (e.g. "./some-lambda") (default: "")
  -I, --dockerImage [DOCKER_IMAGE]                      Docker image for npm ci (default: "")
  -f, --configFile [CONFIG_FILE]                        Path to file holding secret environment variables (e.g. "deploy.env") (default: "")
  -S, --eventSourceFile [EVENT_SOURCE_FILE]             Path to file holding event source mapping variables (e.g. "event_sources.json") (default: "")
  -x, --excludeGlobs [EXCLUDE_GLOBS]                    Space-separated glob pattern(s) for additional exclude files (e.g. "event.json dotenv.sample") (default: "")
  -D, --prebuiltDirectory [PREBUILT_DIRECTORY]          Prebuilt directory (default: "")
  -T, --deployTimeout [DEPLOY_TIMEOUT]                  Deploy Timeout (default: 120000)
  -z, --deployZipfile [DEPLOY_ZIPFILE]                  Deploy zipfile (default: "")
  -B, --deployUseS3 [DEPLOY_USE_S3]                     Use S3 to deploy. (default: false)
  -i, --imageUri [IMAGE_URI]                            URI of a container image in the Amazon ECR registry. (default: "")
  -y, --proxy [PROXY]                                   Proxy server (default: "")
  -A, --tags [AWS_TAGS]                                 Tags as key value pairs (e.g. "tagname1=tagvalue1,tagname2=tagvalue2)" (default: "")
  --silent                                              Silent  or  quiet mode (default: false)
  --no-optionalDependencies                             Run `npm install` with `--no-optional`
  -h, --help                                            display help for command

If you are deploying to a custom endpoint you may also need to pass in an access key/secret. For localstack these can be anything, but cannot be blank:

npx node-lambda@latest deploy --endpoint http://localhost:4574 --accessKey '1234' --secretKey '1234'

Custom Environment Variables

AWS Lambda will let you set environment variables for your function. Use the sample deploy.env file in combination with the --configFile flag to set values which will be added to the lambda configuration upon deploy. Environment variables will also be set when running locally using the same flag

Node.js Runtime Configuration

AWS Lambda now supports Node.js 20, Node.js 18 and Node.js 16. Please also check the Lambda runtimes page.

Use S3 to deploy

Use the command line argument --deployUseS3 or -B. (This option is true/false.) Example: % npx node-lambda@latest deploy -B

You can also set the environment variable DEPLOY_USE_S3. Example: DEPLOY_USE_S3=true

Use the environment variable to set the bucket name or S3 key prefix. The environment variable name is different for each region. Please set it to the environment variable you want to deploy. It can be set in .env.

Example:

# S3_<region>_BUCKET
S3_US_WEST_1_BUCKET=test_aaa

# S3_<region>_PREFIX
S3_US_WEST_1_PREFIX=bbb

In this case, the S3 key: test_aaa/bbb/deploy-package-${FunctionName}.zip

To deploy a container image to Lambda

  1. Pushing a Docker image to ECR
  2. Specify the Image URI of the ECR with the environment variable:IMAGE_URI or --imageUri option, and deploy.

Post install script

When running node-lambda deploy if you need to do some action after npm install --production and before deploying to AWS Lambda (e.g. replace some modules with precompiled ones or download some libraries, replace some config file depending on environment) you can create post_install.sh script. If the file exists the script will be executed (and output shown after execution) if not it is skipped. Environment string is passed to script as first parameter so you can use it if needed. Make sure that the script is executable.

Example post_install.sh:

printf "\n\n######  Post install script  ###### \n"
ENV="production";
if [ ! -z $1 ]
  then
    ENV=$1;
fi
cp -v "config_$ENV.js" "config.js" \
&& printf "######  DONE!  ###### \n\n"

Post invoke script (example)

If you wish to invoke your deployed AWS Lambda function, you can add the following as a script to your package.json:

"invoke:remote": "aws lambda invoke --function-name myLambdaFnName --payload fileb://fixtures/hi.json invoked.json --log-type Tail | jq -r '.LogResult' | base64 --decode && rm invoked.json"

Prebuilt packages

The --prebuiltDirectory flag is useful for working with Webpack for example. It skips npm install --production and post_install.sh and simply packages the specified directory.

Handling npm link and Dependencies With Local Paths

Perhaps the easiest way to handle these cases is to bundle the code using Webpack and use the --prebuiltDirectory flag to package the output for deployment.

ScheduleEvents

Optional Parameter

When using the eventSourceFile flag (-S or --eventSourceFile) to set a ScheduleEvent trigger, you can pass an optional ScheduleDescription key into the ScheduleEvent object with a custom description for the CloudWatch event rule you are defining. By default, node-lambda generates a ScheduleDescription for you based on the ScheduleName and ScheduleExpression of the rule.

Note on ScheduleState for ScheduleEvents

When setting ScheduleState to ENABLED or DISABLED for ScheduleEvents, it is useful to note that this sets the state of the CloudWatch Event rule but DOES NOT set the state of the trigger for the Lambda function you are deploying; ScheduleEvent triggers are enabled by default in the Lambda console when added using the eventSourceFile flag.

Known Issue

Duplicate ScheduleEvent Triggers

If you are adding a trigger via the eventSourceFile for the first time, remove preexisting triggers from the Lambda console before deploying. Deploying a Lambda with the --eventSourceFile flag will NOT overwrite the same triggers created from the AWS console and may result in a duplicate triggers for the same rule.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Added some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Coding style

This project uses JavaScript Standard Style.

JavaScript Style Guide

Running tests

$ npm install
$ npm test

node-lambda's People

Contributors

14pixels avatar abetomo avatar akofman avatar allain avatar amilajack avatar asmt3 avatar benswinburne avatar bigbadtrumpet avatar briandonahue avatar christianklotz avatar ciccia avatar clementkerneur avatar colineberhardt avatar craigsketchley avatar cybercyclone avatar cyrusbowman avatar davemkirk avatar dependabot[bot] avatar deviavir avatar duckworth avatar enriquecanals avatar g-rath avatar gidsg avatar grobmeier avatar guerrerocarlos avatar motdotla avatar navihtot avatar nmaves avatar phm200 avatar swhite24 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-lambda's Issues

Not enough Lambdas

Dudes, you should put es6 lambdas in you lambda code it would be so meta.

Lambda.prototype.zipfileTmpPath = ( program ) => {
  let
  ms_since_epoch = +new Date,
  filename = `${program.functionName}-${ms_since_epoch}.zip`,
  zipfile = path.join( os.tmpDir(), filename );

  return zipfile;
};

Then use harmony flags

VPC Settings

Its great Lambda now supports VPC's. Can node-lambda be updated so we can pass these through?

Zip is not recognized as internal or external command

I am trying to use node-lambda on windows and I am getting this error when trying to deploy using node-lambda deploy. I am sure this will work on linux or mac but how can I deploy on windows. Do I need to install anything.

Deploy options commands overlap "-m"

The deploy -m command overlaps 2 settings. --memorySize works, -m updates mode.

-m, --mode [event] Lambda Mode
-o, --role [your_role] Amazon Role ARN
-m, --memorySize [128] Lambda Memory Size

Zip isn't working on windows

Using git bash. The node-deploy generates some zip (maybe? I can't find the file) but it seems that it's not working.

I'm guessing its because of the paths again. ie

C:/Users/myusername/AppData/Local/Temp/testfunction-1429006026284/node_modules\async\component.json

Update:
I created a temp zip to see what's inside, seems like it maybe working. node-lambda uploading and also manually uploading that zip procudes the same result. A no-working lambda function.

I created the temp zip using Lambda.prototype._zip = function

  fs.writeFileSync('c:/temp/test.zip', data, 'binary');
  return callback(null, 'c:/temp/test.zip');

Update 2:
I'm getting "Service error." from Lambda when trying to invoke this function with the generated zip.

Support 'use strict' at the top of the index file

Some ES6 features ("let" scoping, for example), require 'use strict' to be enabled at the top of the module. When using a config file for environment variables, these are prepended to the file, which causes strict mode to not correctly be enabled. Pull request incoming soon.

passing in --version doesn't work

Not sure if i'm using it correctly or not, but if i try to pass in a value for --version it will just bring up the version of node-lambda not actually set the version of the lambda job on AWS

Specify event source?

Is there a way to specify an event source for the lambda script using node-lambda? There is just AWS_MODE=event afaik.

For example, I would like to specify an S3 event for my lambda script to run when .json gets created in bucket random-bucket. Is there a way to specify this with node-lambda?

make exclude files config external

Currently we need to edit ./lib/main.js to exclude the file we don't want to deploy.

can you make it works like .gitignore?
when first creating a aws-lambda project, run node-lambda init, it will create a .xxignore file, so that we can exclude the files we don't want to deploy.

thank you :)

Deploy function does not include modules from npm link

When in link modules into my project using npm link (symbolic link - used for unpublished local modules), these modules are not included the package uploaded to AWS using node-lambda deploy.
Is it possible to extend node-lambda to include linked modules?

Rename AWS_ROLE ENV variable

The AWS_ROLE variable in the .env file is somewhat misleading, since it actually represents the Role ARN. As a result, it may be a good idea to rename it to AWS_ROLE_ARN for clarity so others in the future don't get an error message:

{ [ValidationException: 1 validation error detected: Value 'worker' at 'role' failed to satisfy constraint: Member must satisfy regular expression pattern: arn:aws:iam::\d{12}:role/?[a-zA-Z_0-9+=,.@\-_/]+]
  message: '1 validation error detected: Value \'worker\' at \'role\' failed to satisfy constraint: Member must satisfy regular expression pattern: arn:aws:iam::\\d{12}:role/?[a-zA-Z_0-9+=,.@\\-_/]+',
  code: 'ValidationException',
  time: Sun Feb 15 2015 21:18:18 GMT-0500 (EST),
  statusCode: 400,
  retryable: false,
  retryDelay: 30 }

That said, the error message was excellent, very descriptive!

InvalidSignatureException on node-lambda deploy

Hello,

I've just stared trying node-lambda, and perhaps I'm missing something. I'm getting the error:

[InvalidSignatureException: The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.

When using node-lambda deploy.

I'm using:

  • OSX 10.11.4
  • node-lambda 0.7.1
  • aws-sdk 2.3.0
  • Tried with node 5.0.0 and 0.10.26

The key/secret used were tested with the Policy Simulator for the LambdaCreateFunction with success.

Anything else I can check or try to overcome this?

Thanks in advance!

Amazon changed the uploadFunction it's now 3 new functions.

http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Lambda.html

Looks like uploadFunction is removed in the current API.

createFunction -> Creates a new Lambda function. If the function name already exists, the operation will fail.
updateFunctionCode -> Updates the code for the specified Lambda function.
updateFunctionConfiguration -> Updates the configuration parameters

Just a note, your code is still working using the old API, for now.

including local requires

I have some shared modules between my microservices where my service my reference something such as:

var myThingy = require('../../myThingy/dist');

Unfortunately these requires are not zipped up. This may actually be impossible but it would be very handy. Is this possible?

Specifying --mode request results in enum error

During deployment, add the argument --mode request and you'll get this error:

[ValidationException: 1 validation error detected: Value 'request' at 'mode' failed to satisfy constraint: Member must satisfy enum value set: [event]]

However, setting the mode to "request" in the .env file works. I'm pretty sure the cli arg should also support "request", not just "event".

Support new Node v4.3 API when running locally

Lambda now supports Node.js v4.3 and it has changed the API, most notably done(), succeed(), fail() are deprecated on the context object in favor of a callback object:

function handler (event, context, callback) {
...
}

node-lambda should support either API based on the AWS_RUNTIME value.

Windows and rsync - deploy issues.

I was trying to get your node-lambda to work, but I am having issues with rsync on my windows machine.

It's not using cygdrive and pathing's are not working.

I'm using git bash. I changed the code to, I realize it's missing the exclude features:

exec('cp -r . ' + codeDirectory, function(err, stdout, stderr) {

post install script

I was compiling native libraries and everything needed to make camanJS work with AWS lambda (caman, canvas, fibers) and I needed a way to copy compiled modules after npm install --production, so I created a fork of this project which allows you to have post_install.sh which (if exists) is runned after npm install --production and before creating a .zip and deploying to lambda.
There is also the npm package node-lambda-postinstall if it helps anyone.
It would be nice to have this option in original project :)

rsync fails for private modules

This line:
https://github.com/motdotla/node-lambda/blob/master/lib/main.js#L162

Assumes that the name of the project is a single identifier but if you're using private npm modules you may end up with a package name such as:

"name": "@example/project-name"

The / in the name ends up generating a bad path here and rsync fails with an error like:

rsync: mkdir "/var/folders/vf/mr4h337s5jb8_w86q8p7372c0000gn/T/@example/project-name-1456433057973" failed: No such file or directory (2)

error during packaging

I startet the package process like this
node-lambda package -e staging -f staging.env

this results into the following error
`
/usr/lib64/node_modules/node-lambda/lib/main.js:270
var handlerFileName = codeDirectory + '/' + program.handler.split('.').shift() + '.js';
^

TypeError: Cannot read property 'split' of undefined
at Lambda._setEnvironmentVars (/usr/lib64/node_modules/node-lambda/lib/main.js:270:62)
at /usr/lib64/node_modules/node-lambda/lib/main.js:357:19
at /usr/lib64/node_modules/node-lambda/lib/main.js:195:7
at FSReqWrap.cb as oncomplete
`

Lambda is not running all the time hence global initialisation happens every time.

I have a lambda where I assign some values to global variables, first time it works fine but second time it again initialises the global variable to default value. How can I run the local lambda like remote serverless lambda.
Also, If one lambda calls to other lambda how both lambdas will be up and running?

Please let me know if there anything I can do to achieve this.

Unable to make http requests

I have a lambda function that uses the firebase sdk to make updates to a firebase backend. This works fine when deployed but when ran locally via node-lambda run there are no errors and everything seems to work but nothing happens in firebase. It seems all outbound calls are muted? Perhaps I'm missing something?

Exclude more directories

Hi, I want to make improvement in deployment. I want to add EXCLUDE_DIRS param to .env file and use it in _rsync function.

Can I implement that?

AWS_ROLE issue

when I run node-module setup, in the generated .env file it has the Key 'AWS_ROLE_ARN'.

When trying to deploy I get an error [ValidationException: 1 validation error detected: Value 'missing' at 'role' failed to satisfy constraint: Member must satisfy regular expression pattern: arn:aws:iam::\d{12}:role/?[a-zA-Z_0-9+=,.@\-_/]+]

The Role was coming through as missing

{
...
Role: 'missing',
...
}

In order to fix this, I just had to switch the AWS_ROLE_ARN to be AWS_ROLE

Right way to handle multiple environments?

I'm a little lost on the philosophy behind how to use this tool to manage different environments (i.e. connecting to a local development database, but then having the deployed version connect to the production database). What I was expecting was to have development.env,staging.env and production.env files, but that doesn't seem like the strategy taken. Any tips to point me in the right direction? Does deploy.env get ignored in development and then can overwrite variables in production?

Using AWS IAM role/user in the lambda

Hi,

Thanks so much for your tool, I love it :)

Just one question about lambda functions requesting other AWS services where authentification is needed (for example cloudsearch with 'aws-sdk" node.js module). Is-it possible to directly specify to node-lambda the IAM role to use in the "run" mode ? I tried to add it to context.json whitout any success :)

If I add the line below in my script it works, but I'm looking for a way to not add it to the JS code :)
AWS.config.update({region:'eu-west-1',accessKeyId: 'XXXX', secretAccessKey: 'XXXX'});
Thanks!
Romain.

Release

Do you plan release new version? It would be nice to have some features like node4.3 runtime support in released version.

Anyway. Thank you for great job!

Deploy doesn't work with namespaced packages

Namespace is interpreted as directory and mkdir is without -p, thereforeit produces Error: Command failed: rsync: mkdir "/tmp/@prefix/package-1446924416224" failed: No such file or directory (2)��

multiple functions per repo

I'm creating a set of related micro-services and would like them all to live under a single git repo. Possibly this is a false hope but is there any way to have subdirectories in a repo (each with a package.json in it) that would work with node-lambda?

When I try it now it traverses up to the root of the git repo instead of to the micro-services subdirectories.

context.succeed is not a function

context.succeed( {test:'foo'} ); is a valid JSON endpoint response under lambda. However, under node-lambda, one instead receives (admittedly this is an svg, not the string foo):

$ ./node_modules/node-lambda/bin/node-lambda run
Running index.handler
==================================
event { key: 'value', key2: 'value2', other_key: 'other_value' }
context { done: [Function] }
==================================
Stopping index.handler
c:\projects\node-lambda-template\index.js:11
  context.succeed( {test:'<svg xmlns="http://www.w3.org/2000/svg" width="500" height="500"><g transform="translate(250,250)"><path class="arc" d="M-14
1.06846055019358,-194.16407864998737A240,240 0 0,1 -4.408728476930471e-14,-240L0,0Z" fill="#5da5da" stroke="#000"></path><path class="arc" d="M-228.25
356391083685,74.1640786499874A240,240 0 0,1 -141.06846055019358,-194.16407864998737L0,0Z" fill="#faa43a" stroke="#000"></path><path class="arc" d="M14
1.06846055019355,194.1640786499874A240,240 0 0,1 -228.25356391083685,74.1640786499874L0,0Z" fill="#60bd68" stroke="#000"></path><path class="arc" d="M
1.469576158976824e-14,-240A240,240 0 0,1 141.06846055019355,194.1640786499874L0,0Z" fill="#b2912f" stroke="#000"></path></g></svg>'} );
          ^

TypeError: context.succeed is not a function
    at exports.handler (c:\projects\node-lambda-template\index.js:11:11)
    at Lambda._runHandler (c:\projects\node-lambda-template\node_modules\node-lambda\lib\main.js:71:3)
    at Lambda.run (c:\projects\node-lambda-template\node_modules\node-lambda\lib\main.js:61:8)
    at Command.<anonymous> (c:\projects\node-lambda-template\node_modules\node-lambda\bin\node-lambda:51:12)
    at Command.listener (c:\projects\node-lambda-template\node_modules\commander\index.js:301:8)
    at emitTwo (events.js:87:13)
    at Command.emit (events.js:172:7)
    at Command.parseArgs (c:\projects\node-lambda-template\node_modules\commander\index.js:615:12)
    at Command.parse (c:\projects\node-lambda-template\node_modules\commander\index.js:458:21)
    at Object.<anonymous> (c:\projects\node-lambda-template\node_modules\node-lambda\bin\node-lambda:64:9)

Am I misusing something?

depoy.env use

the deploy.env is not wokring, i added variables there but i am not able to retrive it using process.env. If its a part of .env it works locally

Deploy precompiled modules?

My dependencies have native extensions that I can't build on my OS X system. I built them on EC2. Now what's the correct way to include these in the deployment?

#!/usr/bin/env node

After installing needed to create a link in /usr/bin for 'node': sudo ln nodejs node
Your file node-lambda/bin/node-lambda begins with the line #!/usr/bin/env node
This did not work on my system.

package.json "main" field seems ignored

The run command still seems to look for index.js even though I've set the "main" field in the package.json file to something other than index.js. Renaming the main.js file to index.js allowed it to run, without changing the "main" field.

Generated zip file omits Unix file permissions - breaks Lambda functions with binaries

If you include a binary file in the package which is meant to be called by the Lambda function it will fail executing the binary as the file permissions are not preserved in the zip.

Lambda will raise the following error message:

{
  "errorMessage": "Process exited before completing request"
}

This is caused by the following error when calling execFile using the child_process package.

[Error: spawn EACCES] code: 'EACCES', errno: 'EACCES', syscall: 'spawn'

I've tried including the platform in the zip options as follows but it doesn't work:

var options = {
    type: 'nodebuffer',
    compression: 'DEFLATE',
    platform: process.platform
  }

The only solution I've come up with so far is using the native zip command. I'm aware that this will work on Unix machines but breaks on Windows. Maybe the following method should only be used on Unix machines based on process.platform?

Lambda.prototype._nativeZip = function(program, codeDirectory, callback) {
  var zipfile = this._zipfileTmpPath(program)
    , cmd = 'zip -r ' + zipfile + ' .'
    , run = exec(cmd, { cwd: codeDirectory }, function (err, stdout, stderr) {
        if (err !== null) {
          callback(err, null)
          return
        }

        var data = fs.readFileSync(zipfile)
        callback(null, data)
    })
}

How to test node.js api locally

i am writing to get information from owner,,i am using express js and making web api using express js...i would like to test api locally same as AWS API Gateway,i need to test conect.done etc locally...amazon lambda have different syntax then normal express api
eg res.json({"Message" : "Welcome to the project"}); but in amazon lambda this type of syntax is not working we need to use content.done like syntax

run debugging?

Is there any way to setup debugging when you use run, I use webstorm and would be very useful.

Inconsistency between ZIP generated with node-lambda package and node-lambda deploy

Hi,

When i generate a ZIP using node-lambda package, then this ZIP contains everything that is currently in my project directory, including .env, deploy.env, event.json ... It also contains files excluded in .env EXCLUDE_GLOBS.
When i deploy to AWS using node-lambda deploy and then download the ZIP file that was uploaded to AWS this file is not the same that was generated with node-lambda package (it no longer contains unnecessary files mentioned above). I would expect the ZIP file created with node-lambda package to be the same as the one uploaded with the deploy command.
Do i misunderstand the package command or is this a bug?

Thanks, Marc

Multiple Lambdas in project

Hey, really like what you've done here. Very elegant solution.

I'd like to update the code a bit to support optional folders with Lambdas inside of them, but still use the simple commands you've laid out for running/deploying.

I.e., right now, only one Lambda per project is supported. I'd like to be able to have many Lambdas in subfolders. My code will not modify the default structure, just support the new optional subfolder structure.

E.g., it would go from only supporting this:

/index.js
/event.json

To also supporting this:

/index.js
/event.json
/module1/index.js
/module1/event.json
/module2/index.js
/module2/event.json
...

And you would be able to run the Lambda in the subfolder by passing in an optional

./node_modules/.bin/node-lambda run --directory module1

Sound like a worthwhile Pull request to you?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.