[CentOS] el7 systemd service:: ensure var/log owner when User is specified

Tue Feb 9 18:05:35 UTC 2021
Jonathan Billings <billings at negate.org>

On Tue, Feb 09, 2021 at 07:21:40PM +0200, Adrian Sevcenco wrote:
> Hi! Does anyone have an idea how can i (in a nice way [1]) to ensure
> ownership/permissions of log directory in /var/log for a unit
> that drops privileges to a user (with User=/Group=)
> [1] The ugly way being with script in StartPre and sudo in Start
> so i want to use User=
> I'm aware of LogsDirectory= but is not available on EL7

Running sudo in a systemd service seems like a bad idea and should be
avoided.  It'll require disabling the RequireTTY feature in the sudo
configuration anyway.

Newer versions of systemd support adding a + or ! at the beginning of
the ExecStart= command to tell systemd to run with elevated
privileges, so you could have:

ExecStartPre=!mkdir -p /var/log/test
ExecStartPre=!chown testuser /var/log/test
ExecStart=/bin/sh -c 'date > /var/log/test/test.log'

However, those features aren't introduced into systemd until ~v231 so
it isn't in EL7.

I think you will have to do something like:

ExecStartPre=mkdir -p /var/log/test
ExecStartPre=chown testuser /var/log/test
ExecStart=su testuser -c 'date > /var/log/test/test.log'

Just don't use sudo.  
Jonathan Billings <billings at negate.org>