How to set environment variables in a systemd unit?
How to set environment variables in a systemd unit?
Define Environment or EnvironmentFile in the systemd unit to set the environment variable directly or have it retrieved from a file.
Systemd units can use environment variables and forward them to an application. To set an enviroment variable, use the Environment or EnvironmentFile option.
Define Environment
The basic option to set an environment variable is using Environment followed by the variable name and value.
[Service]
Environment="MYVAR=hello world"
This defines the variable MYVAR with the value ‘hello world’
Define EnvironmentFile
Environment variables can also be stored within a file by using the option EnvironmentFile. This option might be very useful for automatic deployments, especially if a service unit is used within different environments (such as DEV and PROD). The systemd unit can remain the same, while the file containing the variables needs to be filled with the correct variables and values.
[Service]
EnvironmentFile=/data/env/MYAPP
When using a file to store the environment variables, use the format “VAR=VALUE” (without quotes)