Naar kennisoverzicht

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:

faas-cli new --list Languages available as templates: - csharp - csharp-armhf - dockerfile - go - go-armhf - java8 - node - node-arm64 - node-armhf - php7 - python - python-armhf - python3 - python3-armhf - ruby

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

faas-cli template store list

You can pull one of these with te following command:

faas-cli template store pull <nameOfTemplate>

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:

faas-cli template pull

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:

faas-cli template pull https://github.com/staal-it/openfaas-csharp-injection-template faas-cli new --lang csharp-injection <function name>

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