Course contentsShow
← Linux
Lesson 1312 of 1,81911. Automation and System SchedulingFree lesson

Managing Automation Secrets Safely

Implement secret injection for background tasks without hardcoding sensitive data.

In this lesson, you will learn how to securely pass sensitive credentials like API keys or database passwords to background tasks without baking them into your scripts or configuration files.

The Problem with Hardcoding

When automating tasks with systemd—such as a backup script that uploads files to cloud storage or a service that queries a remote database—you might be tempted to put credentials directly in your bash script. This is a security risk: anyone with read access to the file system can steal your secrets, and they might accidentally be committed to version control.

Using Environment Files

The most efficient way to manage secrets in systemd without writing them into the unit file itself is by using the EnvironmentFile directive.

  1. Create a secure file: Store your secrets in a dedicated file, for example, /etc/systemd/system/backup.env.
  2. Restrict permissions: This is the most critical step. Since this file contains plain-text credentials, set the owner to root and ensure only the owner can read it:
    sudo chmod 600 /etc/systemd/system/backup.env
    
  3. Reference the file in your service: In your service unit file (e.g., /etc/systemd/system/my-backup.service), add the EnvironmentFile directive:
    [Service]
    Type=oneshot
    EnvironmentFile=/etc/systemd/system/backup.env
    ExecStart=/usr/local/bin/backup-script.sh
    

Injecting Secrets into Tasks

Once configured, systemd exports every variable defined in the .env file into the environment of the process started by ExecStart. Your script can now access these values as standard shell variables.

For instance, your backup-script.sh might contain:

#!/bin/bash
# The secret $DB_PASSWORD is now available directly from the environment
curl -u "admin:$DB_PASSWORD" https://api.myserver.com/backup

By decoupling the credentials from the logic, you can update your secrets at any time by simply modifying the .env file and reloading the systemd daemon (systemctl daemon-reload). This approach keeps your code clean, portable, and significantly more secure.

Key Takeaway: Never hardcode credentials in your scripts; instead, store them in restricted-access environment files and inject them into your service units using the EnvironmentFile directive.