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

Start systemd service conditionally?

· 52CE 我爱测

At my organization we have a number of simple-to-use base AMIs for different services such as ECS and Docker. Since many of our projects involve CloudFormation, we're using cfn-bootstrap , which consists of a couple of scripts an…

问题原文

原帖链接 · Naftuli Kay · CC BY-SA 3.0

At my organization we have a number of simple-to-use base AMIs for different services such as ECS and Docker. Since many of our projects involve CloudFormation, we're using cfn-bootstrap, which consists of a couple of scripts and a service which run on boot to install certain packages and do certain configuration management tasks for us.

On startup of a system, an equivalent of the following script must be executed:

#!/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

I was thinking of running this as a systemd oneshot service which runs After=network.target and WantedBy=multi-user.target.

The only problem is that I'd like my AMI to be flexible and only execute this if a certain file exists. Rather than embedding the above script into the EC2 user data, I can have the user data just define an environment file which defines the variables I need and only run my one-shot service if that environment file exists:

#cloud-init
write_files:
    - path: /etc/sysconfig/cloudformation
      # ...
      content: |
          CFN_STACK_NAME="stack-name"
          CFN_RESOURCE="resource-name"
          CFN_REGION="region"

Is there a way to make systemd only run a service if a given condition is met?

已采纳解答

原帖链接 · Michael Hampton · CC BY-SA 4.0

systemd provides a wide variety of conditions you can test. For instance, you can use ConditionPathExists= to test for the existence of a file.

[Unit]
ConditionPathExists=/etc/sysconfig/cloudformation

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

资料来源与适用范围

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

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

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