【问题标题】:systemd env vars from an executable script来自可执行脚本的 systemd env vars
【发布时间】:2017-11-21 12:32:50
【问题描述】:

我有以下 systemd 服务文件:

[Unit]  
Description=My description  

[Service]  
Type=simple  
User=myuser  
ExecStart=/path/to/my/start_script.sh  
ExecStop=/path/to/my/stop_script.sh  
ExecReload=/bin/kill -HUP $MAINPID  
KillMode=process  
Restart=on-failure  
RestartSec=30s  

[Install]  
WantedBy=multi-user.target  

我的 start_script.sh 用于启动 java 应用程序但我需要从可执行的 ksh 脚本中获取一些变量 custom_script.sh

我尝试了以下 systemd 参数但没有成功:

  • ExecStartPre
  • 环境文件

有没有办法让它工作?

先谢谢各位大侠了。

【问题讨论】:

    标签: linux environment-variables systemd


    【解决方案1】:

    为了让您的 Java 进程可以访问来自 custom_script.sh 的变量,您必须以某种方式将它们插入到环境中,以使 systemd 满意。 docs for the EnvironmentFile= directive 表示任何不是带有= 符号的参数赋值语句的行都将被忽略。所以我们需要把你的脚本写下来,这样我们就只剩下运行它后的变量了。

    您可以做的是创建一个辅助“酿酒厂”服务,该服务获取您的custom_script.sh 文件并将环境中的每个值打印到另一个名为custom_script.env 的文件中。然后您可以在EnvironmentFile 指令中将“蒸馏”环境文件提供给Java 进程。

    因此,如果您的原始服务像这样添加After=Requires=

    [Unit]  
    Description=My description  
    After=custom-script-distillery
    Requires=custom-script-distillery
    
    [Service]  
    Type=simple  
    User=myuser  
    EnvironmentFile=/path/to/my/custom_script.env
    ExecStart=/path/to/my/start_script.sh  
    ExecStop=/path/to/my/stop_script.sh  
    ExecReload=/bin/kill -HUP $MAINPID  
    KillMode=process  
    Restart=on-failure  
    RestartSec=30s  
    
    [Install]  
    WantedBy=multi-user.target 
    

    那么酒厂可能是这样的:

    [Unit]
    Description=My service to distill custom_script.sh to an EnvironmentFile
    
    [Service]
    Type=oneshot
    RemainAfterExit=yes
    ExecStart=/bin/bash -c 'set -o allexport; source /path/to/my/custom_script.sh; set +o allexport; unset IFS; set | grep -v "^BASH" > /path/to/my/custom_script.env'
    

    【讨论】:

    • 我最终这样做了:ExecStart=/bin/bash -c 'set -a && source custom_script.sh && start_script.sh ' 非常感谢。
    • 啊,是的,这是个好主意,只要找到它就可以了。
    猜你喜欢
    • 1970-01-01
    • 2020-07-20
    • 1970-01-01
    • 1970-01-01
    • 2019-12-24
    • 2011-07-28
    • 2018-06-07
    • 1970-01-01
    • 2015-08-18
    相关资源
    最近更新 更多