There are multiple approaches to this, another would be to create a "sibling" service that does nothing but determine whether you are in the correct network, fail when you are not which thus does not start your main service or do an ExecStartPre=/ExecCondition= directive but instead of caring about an environment variable, return a non-zero exit code if you are not in the network you want to be which will make ExecStart not get executed.
And the main condition you need to worry about still is invoking this only when you actually have a connection which means you need to depend on network-online.target regardless as otherwise your script and your service will be ran before the network is up and will fail guaranteed.
]]>- I have already tried to use ExecStartPre= and it seems that this is only evaluated in the [Service] section and not in the [Unit] section
- I can use systemctl set-environment only from command line. I need these variables are set at boot time
- system.conf only accepts static variable and not variables defined with a script
What I need is a way to set dynamic calculated variables at boot so the my .service configuration file can evaluate it.
# systemctl set-environment officeNetwork=1
# systemctl start cifscloak.office
definitely works but I need to set this variable automatically at boot based on the default gateway of the network my laptop is connected to.
]]>What you are also going to lack is a way of waiting for the network to be available, which is handled by waiting for network-online.target and activating the relevant invoking service of your networkmanager: https://wiki.archlinux.org/title/System … work_is_up
]]>That being said, global environment variables can be set via /etc/systemd/system.conf.
But again: This is probably not what you really want.
[dellg5 ~]# awk '/default/ {print $3;}' <(ip r)
10.1.1.10
10.1.1.10
awk '/default/ {print $3;}' <(ip r)
[Unit]
After=multi-user.target
Description=cifscloak
ConditionEnvironment=homeNetwork=1
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/bin/cifscloak mount -a -r 6
ExecStop=/usr/bin/cifscloak mount -u -a
[Install]
WantedBy=multi-user.target
ConditionEnvironment should evaluate the homeNetwork variable and start the service if the value is 1.
The problem is, how can I create an instance of this variable in the way the systemd service can read it?
I would like to use something like the following:
gw=$(ip r | grep default | head -1 | awk ' {print $3;}')
if [ "$gw" == "10.1.1.10" ]; then export officeNetwork=1; else export officeNetwork=0; fi
if [ "$gw" == "192.168.1.1" ]; then export homeNetwork=1; else export homeNetwork=0; fi
The problem is: how can I run this script before the systemd service runs?
]]>