This page shows how to use secrets within your functions for API tokens, passwords and similar.
Using secrets is a two step process. First we need to define the secret in your cluster and then you need to 'use' the secret to your function. You can find a simple example function ApiKeyProtected in the OpenFaaS repo. When we deploy this function we provide a secret key that it uses to authenticate requests.
Creating the secret¶
It is generally easiest to read your secret values from files. For our examples we have created a simple text file
~/secrets/secret_api_key.txt that looks like
Now we need to define the secret in the cluster.
Define a secret in Kubernetes¶
In Kubernetes we can leverage the secrets api to safely store our secret values
From the commandline use
kubectl create secret generic secret-api-key --from-file=secret-api-key=~/secrets/secret_api_key.txt
Here we have explicitly named the key of the secret value so that when it is mounted into the function container, it will be named exactly
secret-api-key instead of
Define a secret in Docker Swarm¶
For sensitive value we can leverage the Docker Swarm Secrets feature to safely store our secret values.
From the command line use
docker secret create secret-api-key ~/secrets/secret_api_key.txt
Use the secret in your function¶
Now, update your stack file to include the secret:
provider: name: faas gateway: http://localhost:8080 functions: protectedapi: lang: Dockerfile skip_build: true image: functions/api-key-protected:latest secrets: - secret-api-key
and then deploy
faas-cli deploy -f ./stack.yaml
Once the deploy is done you can test the function using the cli. The function is very simply, it reads the secret value that is mounted into the container for you and then returns a success or failure message based on if your header matches that secret value. For example,
faas-cli invoke protectedapi -H "X-Api-Key=R^YqzKzSJw51K9zPpQ3R3N"
Unlocked the function!
When you use the wrong api key,
faas-cli invoke protectedapi -H "X-Api-Key=thisiswrong"