Systemd – How to Pass a Password to a Unit File

passwordpermissionsshell-scriptsystemd

I would like to start a service using a systemd unit file. This service requires a password to start. I don't want to store the password in plaintext in the systemd unit file, because it is world-readable. I also don't want to provide this password interactively.

If I were writing a normal script for this, I would store the credentials in a file owned by root with restricted permissions (400 or 600), and then read the file as part of the script. Is there any particular systemd-style way to do this, or should I just follow the same process as I would in a regular shell script?

Best Answer

There are two possible approaches here, depending on your requirements. If you do not want to be prompted for the password when the service is activated, use the EnvironmentFile directive. From man systemd.exec:

Similar to Environment= but reads the environment variables from a text file. The text file should contain new-line-separated variable assignments.

If you do want to be prompted, you would use one of the systemd-ask-password directives. From man systemd-ask-password:

systemd-ask-password may be used to query a system password or passphrase from the user, using a question message specified on the command line. When run from a TTY it will query a password on the TTY and print it to standard output. When run with no TTY or with --no-tty it will use the system-wide query mechanism, which allows active users to respond via several agents

Related Question