How to use set_fact to set a new host fact based on when conditionals.

Hi all,

I am trying to set a new host fact (is_master, is_slave) based on comparison of a pre-assigned variable and ansible_hostname fact.

group_vars/

master_hostname: host1

slave_hostname: host2

Tasks

  • name: Set master host fact

set_fact:

is_master: yes

when: master_hostname == ansible_hostname

  • name: Set slave host fact

set_fact:

is_slave: yes

when: slave_hostname == ansible_hostname

  • name: copy master configuration file

template:

src: master.j2

dest: /etc/master.conf

when: is_master == True

  • name: copy slave configuration file

template:

src: slave.j2

dest: /etc/slave.conf

when: is_slave == True

TASK [Gathering Facts] *********************************************************

ok: [host1]

ok: [host2]

TASK [Set is_master variable] ***************************************

ok: [host1]

skipping: [host1]

TASK [Set is_slave variable] ****************************************

skipping: [host2]

ok: [host2]

The goal I am trying to reach is to run certain tasks depending whether the host is master or slave. But these set_fact tasks always get skipped even though condition should be true. Really appreciate your help in pointing out what I am doing wrong.

You’re most likely after inventory_hostname variable (not ansible_hostname).

kind regards
Pshem

using set_fact that way requires you to check if those vars are
defined, i believe this is a better approach:

vars:
  is_master: "{{ inventory_hostname == master_hostname }}"
  is_slave: "{{ inventory_hostname == master_hostname }}"

then you can just use them direcly in subsequent conditionals:

when: is_master|bool

There are other approaches as well, i.e using group_by, but I think
the one above should work best for you.

Hi Brian,

I made the changes based on your suggestions and they work fine. Thank You very much for your help.

Regards,
Alex