A simple Hello, World! with Serverless

A step by step Hello, World! example with the Serverless Framework. Before I start, many of the steps in this walkthrough are in this example from Serverless’ documentation. All the code from this example is available on github in this repo. To do this example you’ll need an active AWS account.

Setting up our environment

First we install the Serverless CLI. To do so you’ll need to follow the steps on this page. This includes installing Node.js on your machine. Run $ serverless --version to verify that your installation was successful.

We then create a directory for our project and navigate inside.

$ mkdir serverless-hello-world
$ cd serverless-hello-world

Let’s make our virtual environment.

$ python3.6 -m venv .

And activate it.

$ source bin/activate

Cool. Now that our virtual environment is up and running we can set the environmental variables that Serverless needs to interact with our AWS account. I typically like to set mine with a .env file, but here we set them directly from the command line. (Note you can also set up your AWS keys with a config file if you prefer)

$ export AWS_ACCESS_KEY_ID=<your-key-here>
$ export AWS_SECRET_ACCESS_KEY=<your-secret-key-here>

The serverless.yml config file

The Serverless Framework uses a YAML config file called serverless.yml to deploy and provision resources. It functions in a similar way that helm charts do for Kubernetes. You define resources and how they are to be tied together in this file, and Serverless does all the heavy lifting of managing the resources for you. In this case Serverless is setting up a CloudFormation template and deploying a Lambda function.

Defining our functions in handler.py

In line 14 in serverless.yml we reference the hello_world function in handler.py. This function is what we actually want to run in Lambda when invoked.

The function itself is quite simple. It receives an event and context object and returns a JSON response body with our “Hello, World!” message.


Serverless makes deployment easy. We’ve already done all the hard work of setting up our configuration file and function logic, so now to deploy we just run this command -

$ sls deploy

That’s it! If you navigate to your AWS console and look in CloudFormation and Lambda you should see the deployed hello-world function.

Making sure it works

All that’s left is to test the deployment. We can invoke the Lambda function directly from the command line with the Serverless CLI.

$ sls invoke -f hello-world

And we get back our Hello, World! message.

"statusCode": 200,
"body": "{\"message\": \"Hello, World!\", \"input\": {}}"