kum*_*mar 7 linux bash systemd
我正在 Docker 环境中试用 systemd 脚本。
考虑一下:
ExecStartPre 更新环境文件中提到的命令和 ExecStart 实际上利用了 env 中提到的环境变量。文件。?(都在同一个 systemd 文件中)。
像这样:
[Unit]
Description=test service
Before=memcached.service
[Service]
Type=oneshot
EnvironmentFile=-/etc/sysconfig/testfile
ExecStartPre=/usr/local/bin/update_sysconfig_testfile.sh
ExecStart=/usr/bin/testmebinary $VOLUMES
[Install]
WantedBy=multi-user.target
Run Code Online (Sandbox Code Playgroud)
这里,$VOLUMES 定义在 testfile 中,它由 update_sysconfig_testfile.sh 脚本更新。
systemd 会知道 ExecStartPre (或)所做的更改它只是加载测试文件中的任何值吗?
如果有更好的方法,请分享。
从 systemd 237 起,只要在文件路径前加上破折号 ( ) 前缀,您就可以在运行ExecStartPre=之前写入EnvironmentFile=一个文件。ExecStart=EnvironmentFile=-/some/path/.env
这似乎是由于评估环境的时间造成的。写诗 说:
环境变量仅在执行时确定
EnvironmentFile=因此,如果执行时未定义,则会出现错误ExecStartPre=,这就是为什么它需要是可选的,但是当“执行时间”到来时ExecStart=,显然会重新检查环境文件并设置环境变量。
这可以更好地记录在man systemd.exec.
您还可以使用文档中man systemd.exec建议的替代方法:Environmentfile=
使用一项 systemd 服务写入环境文件,并使用第二项服务来使用它。使用该部分中的“Before=或”After=关系[Unit],可以确保写入环境文件的服务在引导顺序中首先启动。
with_testfile_vars作为替代方法,请考虑执行以下操作的脚本:
#!/bin/sh
export foo=bar # export the same calculated values you would otherwise write to the file
export baz=qux
exec "$@" # then invoke your "real" program
Run Code Online (Sandbox Code Playgroud)
...使用该包装器的服务文件:
[Unit]
Description=test service
Before=memcached.service
[Service]
Type=oneshot
ExecStart=/usr/local/with_testfile_vars /usr/bin/testmebinary $VOLUMES
[Install]
WantedBy=multi-user.target
Run Code Online (Sandbox Code Playgroud)
根本不需要EnvironmentFile,没有关于它如何解释的顺序依赖性,不用担心 systemd 的解析与 shell 的解析有何不同,等等。