In this lesson, you will learn how to inject dynamic, system-specific configuration into your systemd services using environment files, ensuring your automated tasks remain portable and secure.
Moving Beyond Hardcoding
When managing periodic tasks via systemd timers, it is tempting to hardcode configuration values like database connection strings or API keys directly into your execution script. However, this violates the principle of decoupling execution logic from configuration. Instead, systemd service units allow you to ingest external environment files using the EnvironmentFile= directive.
Implementing Environment Injection
To manage variables, create a dedicated environment file—typically located in /etc/default/ or /etc/systemd/system/. Let’s say you have a backup script that requires a TARGET_DIR variable.
-
Create the Environment File: Create
/etc/default/backup-service.env:TARGET_DIR=/mnt/backups/data RETENTION_DAYS=7 -
Configure the Service Unit: Modify your service unit file (e.g.,
/etc/systemd/system/backup.service) to point to this file:[Service] Type=oneshot EnvironmentFile=/etc/default/backup-service.env ExecStart=/usr/local/bin/backup-script.sh -
Utilize the Variables: Your
backup-script.shcan now access these as standard shell variables, assystemdautomatically exports them into the process environment of your script:#!/bin/bash # The script uses the variables injected by systemd tar -czf "$TARGET_DIR/backup-$(date +%F).tar.gz" /var/www/html find "$TARGET_DIR" -mtime +"$RETENTION_DAYS" -delete
Why This Matters
Using EnvironmentFile provides three major benefits:
- Separation of Concerns: Your script logic remains identical across different servers, while the environment file handles unique paths or credentials.
- Security: You can set restrictive permissions (e.g.,
chmod 600) on the environment file to protect sensitive variables, keeping them out of the script file itself. - Clarity: It centralizes your configuration, making it easier to audit what variables are influencing a background task without parsing through lines of execution code.
Remember that any changes to the environment file or the unit file require a systemctl daemon-reload for the changes to take effect on the next scheduled execution.
Key Takeaway: Use the EnvironmentFile directive in your service units to inject external configuration, decoupling your script logic from environment-specific data while centralizing sensitive settings.