The Fundamental Difference Between Shell Variables and systemd
Many administrators familiar with Bash scripts attempt to use standard environment variables in .service files. This approach fails because systemd parses the unit file during the loading phase, long before any shell is invoked. The systemd parser does not interpret dollar signs as variable references. Consequently, if you write Environment=MY_VAR=value and then try to use $MY_VAR in an ExecStart directive, the literal string $MY_VAR will be passed to the command, likely causing it to fail.
To achieve similar functionality, you must use systemd's native specifier syntax. These specifiers are expanded by the systemd manager itself. They allow you to reference paths, user IDs, group IDs, and other contextual information dynamically. This method is robust because it relies on the service manager's internal state rather than external shell environments.
Using Specifiers for Dynamic Values
Specifiers begin with a percent sign (%). The character immediately following the percent sign determines what value is inserted. For example, %n expands to the full unit name, while %N expands to the pretty unit name. You can combine these with static text to create dynamic paths.
[Service]
ExecStart=/usr/bin/myapp --config /etc/myapp/%n.conf
In this example, if the unit file is named [email protected], the specifier %n might resolve to myapp@web1. The resulting command executed by systemd would be /usr/bin/myapp --config /etc/myapp/[email protected]. This is particularly useful for template units where a single service definition serves multiple instances.
Common Specifiers
- %n: The full unit name (e.g.,
nginx.service). - %N: The pretty unit name (e.g.,
nginx). - %i: The instance name for templated units (the part between @ and .).
- %I: The escaped instance name, suitable for use in filenames.
- %u: The username of the user running the service.
- %g: The group name of the group running the service.
- %t: The user-specific runtime directory (
/run/user/UID). - %T: The system-wide runtime directory (
/run).
Defining Custom Variables with EnvironmentFile
If you need to define custom variables that are not covered by specifiers, such as API keys or database passwords, you should use the EnvironmentFile directive. This directive tells systemd to load key-value pairs from a specified file into the environment of the service process.
[Service]
EnvironmentFile=/etc/myapp/config.env
ExecStart=/usr/bin/myapp --db-host ${DB_HOST}
The file /etc/myapp/config.env should contain lines in the format KEY=VALUE. Note that when referencing these variables in the unit file, you still use the standard shell syntax ${KEY} or $KEY. However, this works because systemd passes these variables to the shell or command via the actual environment block, not through unit file parsing. The unit file parser sees ${DB_HOST} as literal text, but since the command is often executed via a shell (like /bin/sh -c) or the application reads its own environment, the values are available at runtime.
Best Practices for Environment Files
- Use absolute paths for
EnvironmentFile. - Ensure the file permissions restrict access to sensitive data (e.g.,
600). - Use
-EnvironmentFile(with a leading dash) to make the file optional. If the file is missing, systemd will ignore the error instead of failing to start the service.
Interplay with Other Configuration Directives
Variables and specifiers interact with various other directives. For instance, User and Group directives affect which user context the service runs under, which in turn influences specifiers like %u and %g. If you change the user, the runtime directory specifier %t will point to a different path based on the new UID.
Additionally, consider how these variables impact logging and debugging. When troubleshooting why a service failed to start, check the journal logs. Systemd often prints the expanded commands after expansion. This allows you to verify that your specifiers resolved correctly. If you see literal %n in the logs, it indicates a syntax error in your specifier usage.
For more complex dependencies, understanding how services order themselves is crucial. You might need to ensure a configuration file is generated before the service starts. This relates closely to managing shutdown sequences and ensuring proper cleanup of resources.
Preserve Order of Closing Services While Shutting Down Linux provides insight into how timing and ordering affect service stability, which complements the use of dynamic configurations. Similarly, dealing with services that fail to load due to configuration issues requires careful attention to these variable definitions. Systemd Service Not Loaded in Yocto highlights scenarios where embedded systems might have stricter constraints on unit file parsing, making correct variable usage even more critical.Frequently Asked Questions
Can I use $HOME in systemd unit files?
No, you cannot directly use $HOME in the unit file syntax. Instead, use the specifier %t for the user runtime directory or %h for the user home directory. These specifiers are expanded by systemd based on the user defined in the User= directive.
What happens if an EnvironmentFile is missing?
By default, systemd will treat a missing EnvironmentFile as a fatal error and fail to start the service. To prevent this, prefix the filename with a dash, like -EnvironmentFile=/path/to/file. This makes the file optional, allowing the service to start with empty variables if the file is absent.
How do I debug expanded specifiers?
You can inspect the journal logs using journalctl -u service-name. Look for entries that show the final command line after expansion. If you suspect a specifier is not working, try hardcoding the expected value first to isolate whether the issue is with the specifier syntax or the command itself.
Are specifiers safe for filenames?
Most specifiers are safe, but some may contain characters that are problematic for filesystems. Use uppercase specifiers like %I (escaped instance) instead of %i (raw instance) when constructing filenames. The escaped version replaces special characters with underscores, ensuring compatibility across different operating systems and filesystems.
Can I mix specifiers and environment variables?
Yes, you can use both in the same unit file. Specifiers are expanded by systemd during the parsing phase, while environment variables from EnvironmentFile are injected into the process environment at runtime. Ensure you use the correct syntax for each: %specifier for systemd and $VAR for shell/environment references.