Create a Lambda Function with AWS CLI - Complete Guide

avatar

Borislav Hadzhiev

Sat Sep 18 20215 min read

Table of Contents #

  1. Creating the Role of the Lambda Function
  2. Creating the Lambda Function with AWS CLI
  3. Invoking a Lambda Function with AWS CLI
  4. Updating a Lambda Function with AWS CLI
  5. Updating a Lambda Function's Configuration with AWS CLI

Creating the Role of the Lambda Function #

In this article we will create and manage a node.js lambda function using the AWS CLI.

Every lambda function requires an execution role. This is the role the function assumes before it runs.

Let's start by creating the trust policy for the role. In this case the trust policy allows the lambda service to assume the role.

Save the contents of the trust policy in a file named trust-policy.json:

trust-policy.json
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }

Now open your terminal in the directory where trust-policy.json is stored and pass it to the create-role command:

shell
aws iam create-role --role-name lambda-example-role --assume-role-policy-document file://trust-policy.json

create lambda role

Copy and paste the role arn into a notepad, because we'll need it when creating the lambda function.

The next step is to attach a policy to the role. This policy grants permissions to the lambda function to log to CloudWatch.

shell
aws iam attach-role-policy --role-name lambda-example-role --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

attach policy to role

Creating the Lambda Function with AWS CLI #

With the IAM role of the function created, let's create the index.js file, which stores the code for our function:

index.js
exports.handler = async event => { const response = { statusCode: 200, body: JSON.stringify({ greeting: `Hello ${event.name}`, double: event.number * 2, department: process.env.DEPARTMENT, }), }; return response; };

The function expects that we provide the name and number parameters on the event object and set the DEPARTMENT environment variable.

The next step is to zip the code for the function:

shell
zip -r9 lambda.zip index.js

zip lambda

Since our lambda function requires an environment variable called DEPARTMENT, create a file called environment.json, next to your index.js file, with the following json in it:

environment.json
{ "Variables": { "DEPARTMENT": "accounting" } }

Now we're ready to create the lambda function using the AWS CLI. Open your terminal in the directory where the lambda.zip file is stored and run the create-function command:

shell
aws lambda create-function --function-name lambda-example --runtime nodejs14.x --zip-file fileb://lambda.zip --handler index.handler --environment file://environment.json --role "arn:aws:iam::YOUR_ACCOUNT_NUMBER:role/lambda-example-role"

create lambda function

Anytime you pass a local file to an AWS CLI --parameter, you must prefix the file with file:// for human-readable files or fileb:// for binary (non human-readable) files.

In our case, we have prefixed the lambda.zip file with fileb://, because it's binary, non human-readable and the environment.json file with file://, because it's human-readable.

Invoking a Lambda Function with AWS CLI #

Before we invoke the function, we have to store the event properties that the function expects into a file. Our lambda function expects a name and a number property on the event object.

Create a file named event.json with the following json in it:

event.json
{ "name": "John Doe", "number": 42 }

Open your terminal in the directory where even.json is stored and run the invoke command:

shell
aws lambda invoke --function-name lambda-example --cli-binary-format raw-in-base64-out --payload file://event.json response.json

The invoke command takes the following parameters:

NameDescription
function-namethe name of the lambda function
cli-binary-formatby default AWS CLI v2 takes base64 input, but we're passing a raw json string
payloadthe event, the function gets invoked with
response.jsona random name for a file where the function response should be stored

invoke lambda function aws cli

The contents of the response.json file show that the lambda function responds as expected.

Updating a Lambda Function with AWS CLI #

Open your index.js file and update the function's code to:

index.js
exports.handler = async event => { const response = { statusCode: 200, body: JSON.stringify({ greeting: `Howdy ${event.name} ๐Ÿ‘‹`, triple: event.number * 3, department: process.env.DEPARTMENT, }), }; return response; };

Now open your terminal in the directory where the index.js file is located and zip its contents:

shell
zip -r9 lambda.zip index.js

zip lambda

To update a lambda function's code using the AWS CLI, run the update-function-code command:

shell
aws lambda update-function-code --function-name lambda-example --zip-file fileb://lambda.zip

update lambda function aws cli

Now that the function's code has been updated, let's run the invoke command again and look at the function's response:

shell
aws lambda invoke --function-name lambda-example --cli-binary-format raw-in-base64-out --payload file://event.json response.json

invoke updated lambda

The response shows that the function's code has been updated successfully.

Updating a Lambda Function's Configuration with AWS CLI #

Let's update the function to have 1024 MB of RAM (128 is default) and set it's timeout to 5 seconds (3 is default).

To update the function's memory and timeout with the AWS CLI, run the update-function-configuration command.

shell
aws lambda update-function-configuration --function-name lambda-example --timeout 5 --memory-size 1024

update function configuration

Next, let's add environment variables to the function, using the AWS CLI.

Update the contents of the environment.json file to look like:

environment.json
{ "Variables": { "COLOR": "green", "FRUIT": "avocado" } }

To update a function's environment variables, we again use the update-function-configuration command:

shell
aws lambda update-function-configuration --function-name lambda-example --environment file://environment.json --query "Environment"

update lambda environment variables

In the command above, we've used the optional --query parameter to limit the output to only consist of the environment variables of the function.

However if we look at the function's environment variables, we see that our DEPARTMENT env variable is missing.

The update-function-configuration command replaces any existing environment variables with the newly created environment variables.

The way to add environment variables to a function with the AWS CLI, rather than replace them is to first list the function's current environment variables, by running the get-function-configuration command:

shell
aws lambda get-function-configuration --function-name lambda-example --query '{revisionId: RevisionId, env: Environment}'

list lambda environment variables

In the command we've used the --query parameter to filter the output to only relevant properties:

  • the function's environment variables
  • the revisionId, which can be included in the update-function-configuration command and is only used when multiple people work on the same lambda function.

The revisionId prevents the scenario where you would list a function's environment variables and a colleague of yours would update them before you update them, causing a race condition.

It only makes sense to include the revisionId in the update-function-configuration command if there are multiple people working on the same lambda function.

Now that we got the function's environment variables, let's update our environment.json file to include the department variable:

environment.json
{ "Variables": { "COLOR": "green", "FRUIT": "avocado", "DEPARTMENT": "accounting" } }

And finally, let's update the function's environment variable, passing in the revisionId to the update-function-configuration command:

shell
aws lambda update-function-configuration --function-name lambda-example --environment file://environment.json --revision-id "YOUR_REVISION_ID" --query "Environment"

add lambda environment variables

The way the update-function-configuration command works with environment variables applies to lambda layers as well.

Using the command and passing in a layer, replaces any layers the function previously had, rather than adding them.

If you want to read more about using lambda layers with the AWS CLI, read my other article - Create Lambda Layers with AWS CLI

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee