Start SystemD service conditionally?

Naftuli Tzvi Kay asked:

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:


# 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
if [[ $returncode == 0]]; then
    cfn-signal -e $returncode -r "$output"
    exit $returncode

# otherwise, signal success
cfn-signal -s

I was thinking of running this as a SystemD oneshot service which runs and

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:

    - path: /etc/sysconfig/cloudformation
      # ...
      content: |

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

My answer:

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


View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.