Environment variables set by systemd#

Applications sometimes need environment variables to be set for triggering certain behavior like giving debug output or routing traffic via a HTTP-proxy for example. A common way is to modify the start-stop script, but with systemd on most Linux systems, like Debian and Red Hat based distributions, this can also be directly set within the unit file and you don’t have to export the variables anymore.

The Python script below that we run via systemd checks if environment variable VAR1 has been set and will generate different output based on that.

#!/usr/bin/env python3

import os

if os.environ.get('VAR1'):
    a = os.environ['VAR1']
else:
    a = 'default'

print(a)

Running the Python script also shows the output difference as the second command doesn’t print the string “default” anymore to the terminal, but the text “test” that we set via the environment variable.

$ ./main.py
default
$ VAR1=test ./main.py
test

Setting the environment variables via systemd is done by adding the attribute Environment to the Service section of the unit file for the service. After a systemctl daemon-load the environment variable will be set when you start or restart the service.

...
[Service]
Environment="VAR1=hello"
...

If more variables need to be set, then more Environment attributes can be added to the Service section.

...
[Service]
Environment="VAR1=hello"
Environment="VAR2=world"
...

While it may break some human workflows in the beginning, in long term it is a good step for following the infrastructure as code path as Ansible could be used for managing these variables. Also storing these kinds of variables, in the same way, makes both troubleshooting and collecting settings for an audit easier.