To make your Ansible playbook compatible with both Debian-based and Red Hat-based systems, you need to define the systemd_dir variable appropriately for each OS family. You can achieve this using Ansible's vars and set_fact modules, or by leveraging the ansible_os_family fact.
Here's how you can extend your playbook to handle both Debian and Red Hat systems:
1. Using vars and set_fact
You can set the systemd_dir variable based on the OS family using set_fact.
- hosts: your_hosts
become: true
tasks:
- name: Set systemd directory based on OS family
ansible.builtin.set_fact:
systemd_dir: "/etc/systemd/system"
when: ansible_os_family == "RedHat"
- name: Set systemd directory based on OS family
ansible.builtin.set_fact:
systemd_dir: "/lib/systemd/system"
when: ansible_os_family == "Debian"
- name: Write K3s service file
ansible.builtin.template:
src: "k3s-server.service.j2"
dest: "{{ systemd_dir }}/k3s-server.service"
owner: root
group: root
mode: "0644"
register: _k3s_service
2. Using vars with ansible_os_family
Alternatively, you can define the systemd_dir variable directly in the vars section using ansible_os_family.
- hosts: your_hosts
become: true
vars:
systemd_dir: "{{ 'RedHat' in ansible_os_family | default('Debian') | ternary('/etc/systemd/system', '/lib/systemd/system') }}"
tasks:
- name: Write K3s service file
ansible.builtin.template:
src: "k3s-server.service.j2"
dest: "{{ systemd_dir }}/k3s-server.service"
owner: root
group: root
mode: "0644"
register: _k3s_service
3. Using ansible_os_family in the Task
You can also set the systemd_dir directly within the task using ansible_os_family.
- hosts: your_hosts
become: true
tasks:
- name: Write K3s service file
ansible.builtin.template:
src: "k3s-server.service.j2"
dest: "{{ '/etc/systemd/system' if ansible_os_family == 'RedHat' else '/lib/systemd/system' }}/k3s-server.service"
owner: root
group: root
mode: "0644"
register: _k3s_service
Explanation
ansible_os_family: This fact is automatically set by Ansible and contains the OS family of the target system (e.g., RedHat for Red Hat-based systems, Debian for Debian-based systems).
set_fact: This module sets a variable based on a condition.
vars: This section allows you to define variables that can be used throughout the playbook.
- Ternary Operator: The ternary operator (
{{ 'RedHat' in ansible_os_family | default('Debian') | ternary('/etc/systemd/system', '/lib/systemd/system') }}) is used to set the systemd_dir variable based on the OS family.
By using these methods, you can ensure that your playbook works correctly on both Debian and Red Hat-based systems. 🚀