Course contentsShow
← Linux
Lesson 592 of 1,8196. Systemd Internals and Unit OrchestrationFree lesson

Environment Variable Injection

Manage secret and configuration injection into services using EnvironmentFile and drop-in directories.

In this lesson, you will learn how to securely and flexibly inject configuration data into systemd services using EnvironmentFile and drop-in directories.

Decoupling Configuration from Code

When running a service, you often need to provide sensitive data like API keys, database credentials, or specific runtime flags. Hardcoding these into the main unit file (/usr/lib/systemd/system/myapp.service) is a bad practice; it makes the service difficult to update and risks exposing secrets in version control. Instead, we use EnvironmentFile to pull variables from an external text file at runtime.

Using EnvironmentFile

An EnvironmentFile is a simple list of KEY=VALUE pairs. You point your unit file to this path:

[Service]
EnvironmentFile=/etc/default/myapp
ExecStart=/usr/bin/myapp

When systemd starts the service, it reads the file and exports those variables into the process's environment. This keeps your main unit file generic while the environment-specific configuration remains isolated in a separate, easily managed file.

Scaling with Drop-in Directories

While editing the main unit file is possible, it is often overridden by package updates. The professional way to manage these injections is via drop-in directories. If your service is named myapp.service, you can create a directory named /etc/systemd/system/myapp.service.d/.

Inside that directory, create a file named custom.conf:

[Service]
Environment="API_KEY=supersecret123"
EnvironmentFile=/etc/myapp/config.env

By placing these settings in a drop-in file, systemd merges them with the main unit file. This allows you to inject or override variables without ever touching the original distribution-provided unit file. This is safer, cleaner, and ensures your custom configurations survive system updates.

These mechanisms allow you to pass dynamic runtime context to your daemons without modifying the underlying service definition, creating a clear separation between the "logic" of the service and the "data" it requires to function.

Key Takeaway: Use EnvironmentFile to externalize configuration data and drop-in directories to inject settings cleanly without altering the original service unit file.