Creating a simple OpenFaas template

Whenever you want to create a new function to run on OpenFaas your starting point would be an OpenFaas template. OpenFaas has a template engine build-in which can create new functions in a given programming language. There are the official/default templates and there are templates in the store provided by the community. If a language you would like to use isn’t available or it doesn’t suite your needs, you can always write your own! In this post I will show you how I wrote a simple template.

The template store

Before we create our own template, let’s have a look at the template store first. The default/official templates can be listed with the following command:

To list al the templates in the store, you simply run:

You can pull one of these with te following command:

In there store there are various templates written in .Net Core already. If you would like to know more about the template store then have a look at these docs.

A new template

I’ve used the csharp version in my previous blog post. Let’s see how we can write a simple template to enable dependency injection in the default csharp template. As you can see by the length of the remainder of this post, it isn’t too hard…

I started by creating a new folder and downloaded all the existing official templates:

Create a copy of the csharp template as a starting point. In your new template you’ll find a template.yml. This is where you will find the name of your template. I changed mine to csharpinjection. Now it’s time to make changes to the actual implementation of the template. Logical points to make changes are Program.cs, function/FunctionHandler.cs or the Dockerfile. I added a few classes and changed the way the FunctionHandler object is created. It is now instantiated by the dependency injection container which allows you to do constructor injection. I’m not going into any details here. You can find the source on GitHub and it’s pretty straightforward. I’m not sure if it’s a convention but it seems that you should put your template in a ‘template/<nameOfTemple>’ folder in your repo. Once you’ve pushed your template to a repo on GitHub, this how you actually use it to create a new function:

Easy, right?! If you think that the template you’ve created would be beneficial to the community, then please add it to the store.

You may also like...