大网数据广告活动
服务器运维问答

How to use variables in a systemd service file?

· 52CE 我爱测

I'm creating a service file for a daemon, and I would like to use variables (in init scripts I used environment variables) to define some parameters for the executed scripts. For example, I would like to use 2 parameters $PARAM1 …

问题原文

原帖链接 · user886869 · CC BY-SA 3.0

I'm creating a service file for a daemon, and I would like to use variables (in init scripts I used environment variables) to define some parameters for the executed scripts. For example, I would like to use 2 parameters $PARAM1 $PARAM2:

[Unit]
Description=my daemon
After=network.target

[Service]
ExecStart=/usr/local/bin/daemon1
PIDFile=/var/run/daemon1.pid
EnvironmentVariable=PARAM1=123
EnvironmentVariable=PARAM2=444
ExecStartPre=-/usr/bin/wget -O - --post-data=key1=$PARAM1&key2=$PARAM2 http://192.168.1.2/log.php
ExecStopPost=-/usr/bin/wget -O - --post-data=key1=$PARAM1 http://192.168.1.2/log.php
Type=simple

[Install]
WantedBy=multi-user.target

Needless to say, this example doesn't work. Is there something like this achievable with systemd? What kind of parametrization of exec commands is possible?

已采纳解答

原帖链接 · Esa Jokinen · CC BY-SA 3.0

The directive is Environment, not EnvironmentVariable.

Environment=

Sets environment variables for executed processes. Takes a space-separated list of variable assignments. This option may be specified more than once, in which case all listed variables will be set. If the same variable is set twice, the later setting will override the earlier setting.

Environment=PARAM1=123
Environment=PARAM2=444

OR

Environment=PARAM1=123 PARAM2=444

Not sure, but you may need to use them inside braces {}:

--post-data=key1=${PARAM1}&key2=${PARAM2} 

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2017-08-13)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。