In Linux system administration, systemd is a core tool for managing services. In this article I’ll show you how to define environment variables in systemd services so you can configure your programs.
Environment Variables
systemd unit files live in the following directories:
-
/etc/systemd/user/- This is where user-specific files go so systemd can find them. -
/etc/systemd/system/- This is where system-wide files go.
Instead of
/etc/systemd, they can also live in/lib/systemdor/run/systemd, depending on your Linux distribution.
In the [Service] section of the file (for example, my-service.service), define the environment variables with the Environment= directive:
[Service]
Environment="FOO=BAR"
Environment="BAZ=QUX"
Another good way to manage variables is with env files. To do this, first put the path to your file in the service.
[Service]
EnvironmentFile=/path/to/my-service.env
Then, in my-service.env:
FOO=BAR
BAZ=QUX
Make sure you replace /path/to/my-service.env with the actual path to your environment file.
After you change the service file, reload systemd to apply the changes:
sudo systemctl daemon-reload
Finally, start or restart the service so it picks up the environment variables:
sudo systemctl start my-service
Inside the service, you can access the environment variables like any other variable. For example, in a startup script:
#!/bin/bash
echo "The value of FOO is: $FOO"
echo "The value of BAZ is: $BAZ"
This will print:
The value of FOO is: BAR
The value of BAZ is: QUX
Conclusion
Environment variables give you a powerful way to adjust configuration, improve security and stay consistent across environments. They also make CI/CD much easier: you only build the application once, and at deploy time all you need to do is restart the service.
