27.4. Deploying systemd user units by using the systemd RHEL system role
You can create per-user unit files for custom applications, and systemd reads them from the /home/<username>/.config/systemd/user/ directory. By using the systemd RHEL system role, you can automate the deployment of custom unit files for individual users.
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. - The user you specify in the playbook for the systemd unit exists.
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/true RemainAfterExit=yes [Install] WantedBy=multi-user.targetUse 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 for a user ansible.builtin.include_role: name: rhel-system-roles.systemd vars: systemd_unit_file_templates: - item: example.service.j2 user: <username> systemd_enabled_units: - item: example.service user: <username> systemd_started_units: - item: example.service user: <username>重要The
systemdRHEL system role does not create new users, and it returns an error if you specify a non-existent user in the playbook.For 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 --user -M <username>@ status example.service' ... ● example.service - Example systemd service unit file Loaded: loaded (/home/<username>/.config/systemd/user/example.service; enabled; preset: disabled) Active: active (exited) since Wed 2025-03-05 13:33:36 CET; 45s ago ...