0

I want to define a global var (_cfg_chrony) based on Linux distributions: If the OS family is Redhat, define the config path of /etc/chrony.conf; if the OS family is Debian, define the config path of /etc/chrony/chrony.conf

I tried to do something like this at the beginning of my playbook but seems it only applies the last variable and ignores the conditions:

  vars:
    _cfg_chrony: /etc/chrony.conf
    when: ansible_facts['os_family'] == "RedHat"
    _cfg_chrony: /etc/chrony/chrony.conf
    when: ansible_facts['os_family'] == "Debian"

How to setup this properly?

NeilWang
  • 383
  • 4
  • 14
  • why do that in the playbook? Why not create a ansible role and reuse the code? if you have multiple playbooks that needs chrony, you will need to copy and paste :) – c4f4t0r Jul 27 '22 at 08:51
  • @c4f4t0r thanks, I just start using Ansible recently, so not fully understand how a role works in this scenario. But I will read on that. – NeilWang Jul 27 '22 at 22:09

1 Answers1

2

define a fact in tasks

- name: "facts for debian - family"
  set_fact:
    _cfg_chrony: /etc/chrony.conf
  when:
    - ansible_os_family == "Debian"

- name: "facts for RH - family"
  set_fact:
    _cfg_chrony: /etc/chrony/chrony.conf
  when:
    - ansible_os_family == "RedHat"

- name: a task
  ansible.builtin.debug:
    var: _cfg_chrony

or another way shorter but less readable:

- name: a task
  ansible.builtin.debug:
    var: _cfg_chrony
  vars:
    _cfg_chrony: "{{ ('/etc/chrony.conf' if (ansible_os_family == 'Debian')) or ('/etc/chrony/chrony.conf' if (ansible_os_family == 'RedHat')) }}"
exeral
  • 1,787
  • 11
  • 21