Secret management when deploying serverless 12-factor applications

January 1, 2021

First read up on how to deploy openfaas serverlesss functions

12 factor serverless functions

First build your serverless function, and similar to envalid, (which 12factor-env depends on), you can specify your environmental variables.

The main difference is that, you separate the secrets from config vars. This enables 12factor-env to use <SECRET_NAME>_FILE syntax to get your secrets and verify them via envalid.

Create a env.js file in your app:

import { str, email, host, env } from '12factor-env';

export default env(
  process.env,
  {
    // secrets
    MAILGUN_KEY: str()
  },
  {
    // configs
    MAILGUN_DOMAIN: host()
  }
);

Checkout the 12factor-env library for more information and usage.

insert secret into kubernetes

Put your secret in the openfaas-fn namespace, which will ultimately create the file /var/openfaas/secrets/mailgun_key:

kubectl delete secret -n openfaas-fn faas-mailgun-secrets
kubectl create secret \
    generic faas-mailgun-secrets \
    --namespace openfaas-fn \
    --from-literal=mailgun_key=$MAILGUN_KEY

update the OpenFAAS yaml

While OpenFAAS is great, a major downside is that does not support k8s secrets. Alas, this was the inspiration for this post and the creation of 12factor-env.

OpenFAAS instead, similar to docker secrets, stores them as files. Docker defaults secrets to /run/secrets/<secret_name>, however, OpenFAAS stores secrets in /var/openfaas/secrets. The 12factor-env library handles this by allowing you set set ENV_SECRETS_PATH.

You can also set the secret explicitly via MAILGUN_KEY_FILE in this example:

version: 1.0
provider:
  name: openfaas
  gateway: http://gateway-external.openfaas.svc.cluster.local:8080
functions:
  myfunction:
    lang: node12-graphql-private
    handler: ./functions/send-email-link
    image: docker.example.com/pyramation/myfunction:latest
    environment:
      ENV_SECRETS_PATH: /var/openfaas/secrets
      MAILGUN_KEY_FILE: /var/openfaas/secrets/mailgun_key
      scale_from_zero: true
      inactivity_duration: 1m
    secrets:
      - regcred
      - faas-mailgun-secrets

Deploy and now your application will get the MAILGUN_KEY var when you require your env.js file! Enjoy!

sources

https://github.com/pyramation/12factor-env

how to deploy openfaas serverlesss functions


Profile

Written by Dan Lynch an inventor and entrepreneur who loves the web —  follow him on twitter or github