2

Saying that I have two services, which are to start two processes automatically while the system (Ubuntu 16.04.3) starts up.

One service file:

[Unit]
Description=service 1
Requires=init_mdc.service
After=rc.local.service init_mdc.service


[Service]
ExecStart=someCmd
ExecReload=someCmd
KillMode=process
Restart=on-failure
Type=simple

The other service file:

[Unit]
Description=service 2
Requires=init_mdc.service
After=rc.local.service init_mdc.service


[Service]
ExecStart=someCmd2
ExecReload=someCmd2
KillMode=process
Restart=on-failure
Type=simple

The two services need some same env variables.

For now my solution is not good, because the someCmds of the two services are two different bash scripts, in which I set the same env variables.

I'm thinking if I can set some env variables in some place in some way so that the two services can share them, in other words, I want to set the env variables only once, instead of two times.

I've tried to export these env variables from /etc/profile, from /etc/rc.local, but they don't work. I think it's because the system runs my two services first and then /etc/profile and /etc/rc.local are read by the system.

Is there some way to allow me to set some env variables for more than one service file? I've known that we can set EnvironmentFile=XXX in the service file to import some env variables but I don't like this because I still have to set more than once EnvironmentFile=XXX for each service service...

1 Answer 1

0

Using EnvironmentFile= is the way to go.

I don't understand your point on having to set it more than once... You have to set it once from each service that needs those variables...

Service 1:

[Unit]
Description=service 1

[Service]
ExecStart=someCmd
EnvironmentFile=/path/to/common.env
...

Service 2:

[Unit]
Description=service 2

[Service]
ExecStart=someCmd2
EnvironmentFile=/path/to/common.env
...

And keep all the VAR=VALUE settings in file /path/to/common.env.

The syntax of environment file is compatible to that of shell scripts, so you can even have source it in your .bash_profile

# ~/.bash_profile
if [ -f /path/to/common.env ]; then
    . /path/to/common.env
fi

One alternative is to use systemctl set-environment or systemctl import-environment to set global environment variables in PID 1. (See docs here.)

You might still need PassEnvironment= to export those variables in specific services, but in that case you only need to list the variable names.

I really don't think this is the best solution though, I think EnvironmentFile= is much more self-contained, elegant and appropriate for your use case.

1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .