Automating SFTP backup - SystemD script won't work!

I have initialized a repo on an ARM based Synology NAS and am now trying to use SystemD to automate a monthly backup of my Plex server, but am being driven insane.

I tried to follow this tutorial (localizing to suit Ubuntu) but after hours of one problem or another with the SystemD ‘.service’ file I stripped everything right back to this:

Description=Restic backup service
ExecStart=restic -r sftp://user@ --verbose --password-file ~/.config/resticpass.txt backup /var/snap/plexmediaserver/common

Where resticpass.txt only contains the plain text repo password.
Now - this works perfectly in Bash, but not as a systemd oneshot. I find the following error when checking the status of the service after a failed run:
restic[10024]: Resolving password failed: Fatal: ~/.config/resticpass.txt does not exist

Does anyone have any ideas before my brain leaks out my ears?

Obviously, systemd does not resolve ~. I don’t know it by heart how to specify such things, but I would recommend to you either specify the full path in your service description, or consider the systemd manual about paths and environment variables.

Thanks Alex, you must have been right about systemd not resolving ~ But I now get an error with authentication - seems to be some sort of issue with SFTP tunnels created by systemd? I’m using a PSK system.

● restic-backup.service - Restic backup service
     Loaded: loaded (/etc/systemd/system/restic-backup.service; static; vendor preset: enabled)
     Active: failed (Result: exit-code) since Fri 2020-07-17 10:06:40 UTC; 8s ago
    Process: 10719 ExecStart=/usr/bin/restic -r sftp://user@ --verbose --password-file /home/user/.config/resticpass.txt backup /var/snap/plexmediaserver/common (code=exited, status=1/FAILURE)
   Main PID: 10719 (code=exited, status=1/FAILURE)

Jul 17 10:06:39 ubuntu systemd[1]: Starting Restic backup service...
Jul 17 10:06:39 ubuntu restic[10719]: open repository
Jul 17 10:06:40 ubuntu restic[10719]: subprocess ssh: Host key verification failed.
Jul 17 10:06:40 ubuntu restic[10719]: Fatal: unable to open repo at sftp://user@ unable to start the sftp session, error: EOF
Jul 17 10:06:40 ubuntu systemd[1]: restic-backup.service: Main process exited, code=exited, status=1/FAILURE
Jul 17 10:06:40 ubuntu systemd[1]: restic-backup.service: Failed with result 'exit-code'.
Jul 17 10:06:40 ubuntu systemd[1]: Failed to start Restic backup service.

Any thoughts?

Looks like the host key isn’t listed in the known_hosts file that ssh is using. When you test it interactively, are you running it as the same user that systemd is running it as?

I know systemd doesn’t set $HOME all the time, so it might be something to do with that as well - I’m not familiar with exactly what parts of the env are important to ssh.