Create a Systemd unit file with Ansible

Kyle Jones
4 min readOct 17, 2022

--

Let’s create a systemd unit file to create a custom service using Ansible!

After the first post about using Ansible to install and configure Apache, I received a few comments about additional things to implement in the next post. One requested a few changes to the playbook and one other comment that I wanted to have fun with:

Okay, this inspired something silly, my inner troll just kicked in. The systemd unit file we will create today will start and stop the swiping service that will be applied by the swiper role. Yes, we will use the Swiper role to start Swiping…literally. Let’s go!

We Swiping

This playbook will be long so we will develop this playbook as a role. An Ansible role basically segments a complicated playbook into individual segments, where our tasks, handlers, and variables are stored within different directories within our role. Here is a high-level mapped overview:

The above image should help us follow allow with everything below. Each step will be numbered according to the image above. We will start by creating our roles directory and initializing our role “unit”, which I later renamed to “swiper” for comical reasons. Also, note we will create a small nodejs application that pulls the environment variables of the root user. Only implement this in your own personal lab.

1. Defaults: We develop our default variables for this role.

2. Handlers: These are handlers the swiper will call when the notify statement executes when there is a change.

3. Tasks: These are the tasks the swiper role will execute.

4. Template#1: This template is our NodeJs simple app that will be executed when we start the swiping service. This is a basic js app.

5. Template #2: This is the template for our Unit file which will be the actual service for swiping.service

Okay now that we have all of the pieces together for our role, we will now develop the playbook to call the swiper role and start swiping! Here is what this would look like:

Much more simple right?…Right!?

The last step, let’s execute this playbook and call the role:

Everything was executed successfully! We actually created the swiping service on the remote server:

And yes — the app does work! Here is the output when we visit http://ansible1:4000:

Okay now to wrap this up and accomplish what we originally want to do…we want to stop swiping!

Moment of truth!

We officially stopped swiping! In this project, we create an Ansible role, create a systemd unit file, and tapped into our inner troll. Happy Learning!

--

--