Using environment variables and Secrets

Last updated about 2 months ago

Koyeb provides an easy way to provide standard environment variables to containers and functions. This is an excellent way to provide configuration information to your Koyeb functions.

To test environment variables and secrets, we will deploy a container with the standard ubuntu Docker image and print the content of the environment variable with a simple echo.

Environment variables

To test, simply create a Stack and deploy a revision with the following content:

1functions:
2  - name: hello-environment
3    image: ubuntu
4    command: ["bash", "-c"] # Overrides the container default command
5    args: ["echo 'Environment variable MY_ENV_VAR contains: '$MY_ENV_VAR"]
6    env:
7      MY_ENV_VAR: "This a standard environment variable"
8

When you Invoke your function, you shoud have a log message similar to:

12020-09-01T17:27:27.418580266Z stdout F Environment variable MY_ENV_VAR contains: This a standard environment variable
2

Access secrets through an environment variable in a Stack function

You can expose Secrets through environment variables available at runtime in your Stack functions. Using Secrets in Stack functions is essential to avoid storing credentials in clear plain-text in your stack configuration files and git repositories. Secrets can also be used to ease maintenance for configuration variables.

Creating Secrets can be done through the Secrets section in the left menu. Let's start by creating a Secret with the following name and value:

  • Name: my-first-secret
  • Secret: My Precious

If you need help, check out the Create a Secret guide.

We now have a secret called my-first-secret and can deploy a new revision:

1functions:
2  - name: hello-secret
3    image: ubuntu
4    command: ["bash", "-c"] # Overrides the container default command
5    args: ["echo 'This is stored in a secure fashion: '$MY_SECRET"]
6    env:
7      MY_SECRET:
8        value_from_secret: my-first-secret
9

Invoking your function should give you a log message similar to:

12020-09-01T15:32:37.335347459Z stdout F This is stored in a secure fashion: My Precious
2

Use Secret as Volumes

Another way to access your Secret is to read them through a file available in your function with volumes.

We will mount our previous Secret as a volume and execute a ls /koyeb/secrets/ to view the file system structure and display the Secret using cat.

1  - name: hello-vol-secret
2    image: ubuntu
3    command: ["bash", "-c"] # Overrides the container default command
4    args: ["echo 'This is stored in a secure fashion:' && ls /koyeb/secrets && cat /koyeb/secrets/my-first-secret "]
5    volumes:
6      - secret: my-first-secret
7

Invoking your function should give you a log message similar to:

12020-08-25T10:01:52.841344385Z stdout F This is stored in a secure fashion:
22020-08-25T10:01:52.921023274Z stdout F my-first-secret
32020-08-25T10:01:52.928251624Z stdout P My Precious
4
footer-frame