How do I assign the result of curl to a systemd variable?

mattm asked:

I am using an Amazon Web Service server, and am trying to setup a systemd job that takes as an input the AWS external IP retrieved by curl.

[Unit]
Description=My example with AWS external IP
Wants=network-online.target
After=network-online.target

[Service]
Type=forking
Environment=EXTERNAL_IP=$(/usr/bin/curl http://169.254.169.254/latest/meta-data/public-ipv4)
ExecStart=/path/to/myexample $EXTERNAL_IP

[Install]
WantedBy=multi-user.target

The verify tool systemd-analyze verify myexample.service indicates there is a problem with curl and the environment assignment.

Invalid environment assignment, ignoring: EXTERNAL_IP=$(/usr/bin/curl http://169.254.169.254/latest/meta-data/public-ipv4)

If I replace the curl result with a hard-coded IP string, my daemon starts. How can I use the curl result in my systemd job?

My answer:


(First, I presume you are using coturn or one of its predecessors.)

To begin with, systemd units are not shell scripts and aren’t parsed by a shell. This is why you can’t just call a command and use its output as an environment variable.

However, you can call a shell from ExecStart=, which might be the fastest way to get up and running.

Type=simple
ExecStart=/bin/bash -c '/usr/local/bin/turnserver -X $(/usr/bin/curl http://169.254.169.254/latest/meta-data/public-ipv4)'

(In this configuration you should not daemonize turnserver with -o.)

You could also write a script, which you can call from ExecStartPre=, which fetches your metadata and then alters turnserver.conf, which would occur before the daemon is started.


View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.