有条件地启动systemd服务?

Naf*_*Kay 16 systemd

在我的组织中,我们有许多易于使用的基础 AMI,用于不同的服务,例如 ECS 和 Docker。由于我们的许多项目都涉及 CloudFormation,我们正在使用cfn-bootstrap,它由几个脚本和一个服务组成,这些脚本和服务在启动时运行以安装某些包并为我们执行某些配置管理任务。

在系统启动时,必须执行与以下脚本等效的脚本:

#!/bin/bash

# capture stderr only
output="$(cfn-init -s $STACK_NAME -r $RESOURCE_NAME --region $REGION >/dev/null)"

# if it failed, signal to CloudFormation that it failed and include a reason
returncode=$?
if [[ $returncode == 0]]; then
    cfn-signal -e $returncode -r "$output"
    exit $returncode
fi

# otherwise, signal success
cfn-signal -s
Run Code Online (Sandbox Code Playgroud)

我想把它作为一个 systemdoneshot服务来运行After=network.target,它运行WantedBy=multi-user.target.

唯一的问题是我希望我的 AMI 是灵活的,并且只有在某个文件存在时才执行它。与其将上述脚本嵌入到 EC2 用户数据中,我还可以让用户数据只定义一个环境文件,该文件定义了我需要的变量,并且如果该环境文件存在,则仅运行我的一次性服务:

#cloud-init
write_files:
    - path: /etc/sysconfig/cloudformation
      # ...
      content: |
          CFN_STACK_NAME="stack-name"
          CFN_RESOURCE="resource-name"
          CFN_REGION="region"
Run Code Online (Sandbox Code Playgroud)

有没有办法让 systemd 只在满足给定条件的情况下运行服务?

Mic*_*ton 21

systemd 提供了多种可以测试的条件。例如,您可以ConditionPathExists=用来测试文件是否存在。

[Unit]
ConditionPathExists=/etc/sysconfig/cloudformation
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,这不是“while”条件,而是“if”,这意味着如果“ConditionPathExists”中指定的路径在服务启动时不存在,则服务的其余部分将不会运行。即,它不会等待路径存在。 (4认同)
  • @Mahn 看看 https://www.freedesktop.org/software/systemd/man/systemd.path.html#。它可以监视路径并提供基于例如路径何时存在的激活。 (2认同)