27.3. Deploying systemd units by using the systemd RHEL system role
You can create unit files for custom applications, and systemd reads them from the /etc/systemd/system/ directory. By using the systemd RHEL system role, you can automate the deployment of custom unit files.
Prerequisites
- You have prepared the control node and the managed nodes.
- You are logged in to the control node as a user who can run playbooks on the managed nodes.
-
The account you use to connect to the managed nodes has
sudopermissions for these nodes.
Procedure
Create a Jinja2 template with the custom systemd unit file contents. For example, create the
~/example.service.j2file with the contents for your service:{{ ansible_managed | comment }} [Unit] Description=Example systemd service unit file [Service] ExecStart=/bin/trueUse the
<name>.<unit_type>.j2convention for the file name. For example, to create theexample.serviceunit, you must name the fileexample.service.j2. Place the file in the same directory as the playbook.Create a playbook file, for example,
~/playbook.yml, with the following content:--- - name: Managing systemd services hosts: managed-node-01.example.com tasks: - name: Deploy, enable, and start a custom systemd service ansible.builtin.include_role: name: redhat.rhel_system_roles.systemd vars: systemd_unit_file_templates: - example.service.j2 systemd_enabled_units: - example.service systemd_started_units: - example.serviceFor details about all variables used in the playbook, see the
/usr/share/ansible/roles/rhel-system-roles.systemd/README.mdfile on the control node.Validate the playbook syntax:
$ ansible-playbook --syntax-check ~/playbook.ymlNote that this command only validates the syntax and does not protect against a wrong but valid configuration.
Run the playbook:
$ ansible-playbook ~/playbook.yml
Verification
Verify that the service is enabled and started:
# ansible managed-node-01.example.com -m command -a 'systemctl status example.service' ... ● example.service - A service for demonstrating purposes Loaded: loaded (/etc/systemd/system/example.service; enabled; vendor preset: disabled) Active: active (running) since Thu 2024-07-04 15:59:18 CEST; 10min ago ...