1

I am trying to use a ready-made bash script that sets env. This is the service that I'm trying to use:

[Unit]
Description=myserver service
After=multi-user.target

[Service]
Type=simple
User=ec2-user
Group=ec2-user
WorkingDirectory=/home/ec2-user/myserver/
ExecStart=/bin/sh -c '/home/ec2-user/myserver/config/myserverVars.sh ;/home/ec2-user/venv/bin/python  /home/ec2-user/myserver/myserver.py 2>&1 >> /home/ec2-user/myserver/logs/systemd_myserver.log' 
StandardOutput=append:/home/ec2-user/myserver/logs/systemd_stdout.log
StandardError=append:/home/ec2-user/myserver/logs/systemd_stderr.log

[Install]
WantedBy=multi-user.target

The myserverVars.sh:

#!/bin/bash
export APP1=foo@gmail.com
export APP2_BIND_PASS=xxxxxx
export APP3=xxxxxx

the variables in /home/ec2-user/myserver/config/myserverVars.sh
are never set, and the server is started without the variables and this is wrong. I am trying to avoid using Environment key or Environment File.

1
  • Note that Environment is the native mechanism in systemd, and the service unit file is intended to directly contain environment settings. The systemd people consider EnvironmentFile to have been a mistake, but conversely Environment is the way to set environment variables, either directly or with drop-in "snippet" files. unix.stackexchange.com/a/557081/5132
    – JdeBP
    Jun 12 '20 at 13:10
1

If you want variables defined in a script file to be available to the parent environment running that script, you need to source the script, not execute it. Change your ExecStart line to:

ExecStart=/bin/sh -c '. /home/ec2-user/myserver/config/myserverVars.sh ;/home/ec2-user/venv/bin/python  /home/ec2-user/myserver/myserver.py >> /home/ec2-user/myserver/logs/systemd_myserver.log 2>&1 ' 

See What is the difference between sourcing ('.' or 'source') and executing a file in bash? for details on the difference between sourcing and executing a script.

Also note that I changed the order of redirections. To get both stderr and stdout to the same file, you need > file 2>&1 not 2>&1 > file.

3
  • any way to format this long string to something readble ? with line breaks "\"
    – user63898
    Jun 11 '20 at 13:39
  • @user63898 I don't know, did you try it with line breaks? If they dont' work, please ask a new question since that is a completely separate topic.
    – terdon
    Jun 11 '20 at 14:06
  • Of course, the redirections are a bad idea in the first place, as service management systems handle logging standard output/error. And there should be an exec in the invocation of python, to cope with the case that /bin/sh is the Bourne Again shell.
    – JdeBP
    Jun 12 '20 at 13:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.