UNPKG

16.6 kBMarkdownView Raw
1# node-lambda
2
3![node-lambda](../master/node-lambda.png?raw=true)
4
5Command line tool to locally run and deploy your node.js application to [Amazon Lambda](http://aws.amazon.com/lambda/).
6
7![Node CI](https://github.com/motdotla/node-lambda/workflows/Node%20CI/badge.svg)
8[![BuildStatus](https://travis-ci.org/motdotla/node-lambda.svg?branch=master)](https://travis-ci.org/motdotla/node-lambda)
9[![NPM version](https://badge.fury.io/js/node-lambda.svg)](http://badge.fury.io/js/node-lambda)
10
11```
12$ node-lambda run
13```
14
15## Installation
16
17```
18$ npm install -g node-lambda
19```
20
21## Example App
22
23Example apps make it easy to get up and running
24* [JavaScript example](https://github.com/motdotla/node-lambda-template).
25* [TypeScript example](https://github.com/fogfish/node-lambda-typescript-template).
26
27## Usage
28
29There are 4 available commands.
30
31```
32$ node-lambda setup
33$ node-lambda run
34$ node-lambda package
35$ node-lambda deploy
36```
37
38### Commands
39
40#### setup
41
42Initializes 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).
43
44```
45$ node-lambda setup --help
46
47Usage: setup [options]
48
49Sets up the .env file.
50
51
52Options:
53 -h, --help output usage information
54 -j, --eventFile [event.json] Event JSON File
55 -x, --contextFile [context.json] Context JSON File
56```
57
58After running setup, it's a good idea to gitignore the generated `event.json` and `.env` files, as well as `.lambda`.
59
60```
61$ echo -e ".env\ndeploy.env\nevent.json\n.lambda" >> .gitignore
62```
63
64##### Deploy env variables
65
66```
67PACKAGE_MANAGER // (default: 'npm')
68AWS_ENVIRONMENT // (default: '')
69AWS_ENDPOINT // (default: '')
70CONFIG_FILE // (default: '')
71EVENT_SOURCE_FILE // (default: '')
72EXCLUDE_GLOBS // (default: '')
73AWS_ACCESS_KEY_ID // (default: not set!)
74AWS_SECRET_ACCESS_KEY // (default: not set!)
75AWS_PROFILE = // (default: '')
76AWS_SESSION_TOKEN = // (default: '')
77AWS_REGION = // (default: 'us-east-1,us-west-2,eu-west-1')
78AWS_FUNCTION_NAME // (default: package.json.name or 'UnnamedFunction')
79AWS_HANDLER // (default: 'index.handler')
80AWS_ROLE_ARN || AWS_ROLE // (default: 'missing')
81AWS_MEMORY_SIZE // (default: 128)
82AWS_TIMEOUT // (default: 60)
83AWS_RUN_TIMEOUT // (default: 3)
84AWS_ARCHITECTURE // (default: 'x86_64')
85AWS_DESCRIPTION // (default: package.json.description or '')
86AWS_RUNTIME // (default: 'nodejs16.x')
87AWS_PUBLISH // (default: false)
88AWS_FUNCTION_VERSION // (default: '')
89AWS_VPC_SUBNETS // (default: '')
90AWS_VPC_SECURITY_GROUPS // (default: '')
91AWS_TRACING_CONFIG // (default: '')
92AWS_LAYERS // (default: '')
93AWS_LOGS_RETENTION_IN_DAYS // (default: '')
94EVENT_FILE // (default: 'event.json')
95PACKAGE_DIRECTORY // (default: not set)
96CONTEXT_FILE // (default: 'context.json')
97PREBUILT_DIRECTORY // (default: '')
98SRC_DIRECTORY // (default: '')
99DEPLOY_TIMEOUT // (default: '120000')
100DOCKER_IMAGE // (default: '')
101DEPLOY_ZIPFILE // (default: '')
102DEPLOY_USE_S3 // (default: false)
103IMAGE_URI // (default: '')
104AWS_DLQ_TARGET_ARN // (default: not set)
105AWS_TAGS // (default: '')
106```
107
108#### run
109
110Runs your Amazon Lambda index.js file locally. Passes `event.json` data to the Amazon Lambda event object.
111
112```
113$ node-lambda run --help
114Usage: node-lambda run|execute [options]
115
116Run your Amazon Lambda application locally
117
118Options:
119 -H, --handler [AWS_HANDLER] Lambda Handler {index.handler} (default: "index.handler")
120 -j, --eventFile [EVENT_FILE] Event JSON File (default: "event.json")
121 -u, --runtime [AWS_RUNTIME] Lambda Runtime (default: "nodejs16.x")
122 -t, --timeout [AWS_RUN_TIMEOUT] Lambda Timeout (default: 3)
123 -f, --configFile [CONFIG_FILE] Path to file holding secret environment variables (e.g. "deploy.env") (default: "")
124 -x, --contextFile [CONTEXT_FILE] Context JSON File (default: "context.json")
125 -M, --enableRunMultipleEvents [ENABLE_RUN_MULTIPLE_EVENTS] Enable run multiple events (default: true)
126 -y, --proxy [PROXY] Proxy server (default: "")
127 --apiGateway Convert to API Gateway events (default: false)
128 -h, --help display help for command
129```
130
131#### package
132
133Bundles your application into a local zip file.
134
135```
136$ node-lambda package --help
137Usage: node-lambda package|zip [options]
138
139Create zipped package for Amazon Lambda deployment
140
141Options:
142 --packageManager [PACKAGE_MANAGER] Package manager used to install dependencies (default: "npm", options: "npm", "yarn")
143 -A, --packageDirectory [PACKAGE_DIRECTORY] Local Package Directory
144 -I, --dockerImage [DOCKER_IMAGE] Docker image for npm ci (default: "")
145 -n, --functionName [AWS_FUNCTION_NAME] Lambda FunctionName (default: "node-lambda")
146 -H, --handler [AWS_HANDLER] Lambda Handler {index.handler} (default: "index.handler")
147 -e, --environment [AWS_ENVIRONMENT] Choose environment {dev, staging, production} (default: "")
148 -x, --excludeGlobs [EXCLUDE_GLOBS] Space-separated glob pattern(s) for additional exclude files (e.g.
149 "event.json dotenv.sample") (default: "")
150 -D, --prebuiltDirectory [PREBUILT_DIRECTORY] Prebuilt directory (default: "")
151 -m, --keepNodeModules [KEEP_NODE_MODULES] Keep the current node_modules directory. (default: false)
152 -v, --dockerVolumes [DOCKER_VOLUMES] Additional docker volumes to mount. Each volume definition has to be
153 separated by a space (e.g. "$HOME/.gitconfig:/etc/gitconfig
154 $HOME/.ssh:/root/.ssh") (default: "")
155 --no-optionalDependencies Run `npm install` with `--no-optional`
156 -h, --help display help for command
157```
158
159#### deploy
160
161Bundles and deploys your application up to Amazon Lambda.
162
163```
164$ node-lambda deploy --help
165Usage: node-lambda deploy [options]
166
167Deploy your application to Amazon Lambda
168
169Options:
170 --packageManager [PACKAGE_MANAGER] Package manager used to install dependencies (default: "npm", options: "npm", "yarn")
171 -e, --environment [AWS_ENVIRONMENT] Choose environment {dev, staging, production} (default: "")
172 -E, --endpoint [AWS_ENDPOINT] Choose endpoint (e.g. localstack, "http://127.0.0.1:4574") (default: "")
173 -a, --accessKey [AWS_ACCESS_KEY_ID] AWS Access Key
174 -s, --secretKey [AWS_SECRET_ACCESS_KEY] AWS Secret Key
175 -P, --profile [AWS_PROFILE] AWS Profile (default: "")
176 -k, --sessionToken [AWS_SESSION_TOKEN] AWS Session Token (default: "")
177 -r, --region [AWS_REGION] AWS Region (default: "us-east-1,us-west-2,eu-west-1")
178 -n, --functionName [AWS_FUNCTION_NAME] Lambda FunctionName (default: "node-lambda")
179 -H, --handler [AWS_HANDLER] Lambda Handler {index.handler} (default: "index.handler")
180 -o, --role [AWS_ROLE] Amazon Role ARN (default: "missing")
181 -m, --memorySize [AWS_MEMORY_SIZE] Lambda Memory Size (default: 128)
182 -t, --timeout [AWS_TIMEOUT] Lambda Timeout (default: 60)
183 --architecture [AWS_ARCHITECTURE] The instruction set architecture that the function supports. (x86_64|arm64) (default: "x86_64")
184 -d, --description [AWS_DESCRIPTION] Lambda Description (default: "Command line tool for locally running and remotely deploying your node.js applications to Amazon Lambda.")
185 -u, --runtime [AWS_RUNTIME] Lambda Runtime (default: "nodejs16.x")
186 -p, --publish [AWS_PUBLISH] Lambda Publish (default: false)
187 -L, --lambdaVersion [AWS_FUNCTION_VERSION] Lambda Function Version (default: "")
188 -b, --vpcSubnets [AWS_VPC_SUBNETS] Lambda Function VPC Subnet IDs (comma delimited) (default: "")
189 -g, --vpcSecurityGroups [AWS_VPC_SECURITY_GROUPS] Lambda VPC Security Group IDs (comma delimited) (default: "")
190 -K, --kmsKeyArn [AWS_KMS_KEY_ARN] Lambda KMS Key ARN (default: "")
191 -Q, --deadLetterConfigTargetArn [AWS_DLQ_TARGET_ARN] Lambda DLQ resource
192 -c, --tracingConfig [AWS_TRACING_CONFIG] Lambda tracing settings (default: "")
193 -l, --layers [AWS_LAYERS] Lambda Layers settings (e.g. "ARN1,ARN2[,..])" (default: "")
194 -R, --retentionInDays [AWS_LOGS_RETENTION_IN_DAYS] CloudWatchLogs retentionInDays settings (default: "")
195 -G, --sourceDirectory [SRC_DIRECTORY] Path to lambda source Directory (e.g. "./some-lambda") (default: "")
196 -I, --dockerImage [DOCKER_IMAGE] Docker image for npm ci (default: "")
197 -f, --configFile [CONFIG_FILE] Path to file holding secret environment variables (e.g. "deploy.env") (default: "")
198 -S, --eventSourceFile [EVENT_SOURCE_FILE] Path to file holding event source mapping variables (e.g. "event_sources.json") (default: "")
199 -x, --excludeGlobs [EXCLUDE_GLOBS] Space-separated glob pattern(s) for additional exclude files (e.g. "event.json dotenv.sample") (default: "")
200 -D, --prebuiltDirectory [PREBUILT_DIRECTORY] Prebuilt directory (default: "")
201 -T, --deployTimeout [DEPLOY_TIMEOUT] Deploy Timeout (default: 120000)
202 -z, --deployZipfile [DEPLOY_ZIPFILE] Deploy zipfile (default: "")
203 -B, --deployUseS3 [DEPLOY_USE_S3] Use S3 to deploy. (default: false)
204 -i, --imageUri [IMAGE_URI] URI of a container image in the Amazon ECR registry. (default: "")
205 -y, --proxy [PROXY] Proxy server (default: "")
206 -A, --tags [AWS_TAGS] Tags as key value pairs (e.g. "tagname1=tagvalue1,tagname2=tagvalue2)" (default: "")
207 --silent Silent or quiet mode (default: false)
208 --no-optionalDependencies Run `npm install` with `--no-optional`
209 -h, --help display help for command
210```
211
212If 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:
213
214```
215node-lambda deploy --endpoint http://localhost:4574 --accessKey '1234' --secretKey '1234'
216```
217
218## Custom Environment Variables
219
220AWS 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
221
222## Node.js Runtime Configuration
223
224AWS Lambda now supports Node.js 16 and Node.js 14. Please also check the [Lambda runtimes](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html) page.
225
226## Use S3 to deploy
227
228Use the command line argument `--deployUseS3` or `-B`. (This option is true/false.)
229Example: `% node-lambda deploy -B`
230
231You can also set the environment variable `DEPLOY_USE_S3`.
232Example: `DEPLOY_USE_S3=true`
233
234Use the environment variable to set the bucket name or S3 key prefix.
235The environment variable name is different for each region. Please set it to the environment variable you want to deploy.
236It can be set in `.env`.
237
238Example:
239
240```sh
241# S3_<region>_BUCKET
242S3_US_WEST_1_BUCKET=test_aaa
243
244# S3_<region>_PREFIX
245S3_US_WEST_1_PREFIX=bbb
246```
247
248In this case, the S3 key:
249`test_aaa/bbb/deploy-package-${FunctionName}.zip`
250
251## To deploy a container image to Lambda
252
2531. [Pushing a Docker image to ECR](https://docs.aws.amazon.com/AmazonECR/latest/userguide/docker-push-ecr-image.html)
2542. Specify the Image URI of the ECR with the environment variable:`IMAGE_URI` or `--imageUri` option, and deploy.
255
256## Post install script
257When 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.
258
259Example `post_install.sh`:
260```
261printf "\n\n###### Post install script ###### \n"
262ENV="production";
263if [ ! -z $1 ]
264 then
265 ENV=$1;
266fi
267cp -v "config_$ENV.js" "config.js" \
268&& printf "###### DONE! ###### \n\n"
269```
270
271## Post invoke script (example)
272If you wish to invoke your deployed AWS Lambda function, you can add the following as a `script` to your `package.json`:
273
274```
275"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"
276```
277
278## Prebuilt packages
279The `--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.
280
281## Handling `npm link` and Dependencies With Local Paths
282Perhaps 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.
283
284## ScheduleEvents
285#### Optional Parameter
286When 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.
287
288#### Note on ScheduleState for ScheduleEvents
289When 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.
290
291#### Known Issue
292###### Duplicate ScheduleEvent Triggers
293If 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.
294
295## Other AWS Lambda Tools Projects
296
297+ [lambdaws](https://github.com/mentum/lambdaws)
298+ [lambdaws-instant-api](https://github.com/mentum/lambdaws-instant-api)
299
300## Contributing
301
3021. Fork it
3032. Create your feature branch (`git checkout -b my-new-feature`)
3043. Commit your changes (`git commit -am 'Added some feature'`)
3054. Push to the branch (`git push origin my-new-feature`)
3065. Create new Pull Request
307
308### Coding style
309This project uses [JavaScript Standard Style](https://standardjs.com/).
310
311[![JavaScript Style Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)
312
313## Running tests
314
315```
316$ npm install
317$ npm test
318```