How to use custom fact in Ansible dynamically to evaluate conditional statement

Viewed 126

I'm trying to evaluate the condition

hostvars[inventory_hostname].external_ip == ansible_facts['ipify_ip']

The external_ip is set on the host_variable . I have set the ipify_ip on the custom facts and trying to evaluate this condition

when: hostvars[inventory_hostname].external_ip == ansible_facts['ipify_ip']

I have tried this option also but it failed there too

when: hostvars[inventory_hostname].external_ip == {{ ipify_ip }}

Here is the complete playbook file

- name: Get public ip for the host
  ipify_facts:
   api_url: https://api.ipify.org/
   timeout: 20
  tags: always

- name: Set fact
  set_fact:
   ipify_ip: "{{ ipify_public_ip }}"
  tags: always

- name: ipify_ip External IP
  debug:
   var: ipify_ip
  tags: always

- name: is extrnal_ip in hostvars is same with ipify_ip
  debug:
   var=hostvars[inventory_hostname].external_ip
  when: hostvars[inventory_hostname].external_ip == ansible_facts['ipify_ip']
  tags: always

The error

fatal: [localhost]: FAILED! => {"msg": "The conditional check 'hostvars[inventory_hostname].external_ip == ansible_facts['ipify_ip']' failed. The error was: error while evaluating conditional (hostvars[inventory_hostname].external_ip == ansible_facts['ipify_ip']): 'dict object' has no attribute 'ipify_ip'\n\nThe error appears to be in '/home/anish/playbook/prereqs.yml': line 29, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - name: extrnal_ip on hostvars\n ^ here\n"}

What is the right way to do this ??

1 Answers

Simply use the variables. For example, given the inventory

shell> cat hosts
host01 external_ip=1.2.3.4

and the playbook

shell> cat playbook.yml
- hosts: host01
  tasks:
    - set_fact:
        ipify_ip: 1.2.3.4
    - debug:
        var: ipify_ip
    - debug:
        var: external_ip
    - debug:
        msg: "{{ external_ip }} is equal to {{ ipify_ip }}"
      when:  external_ip == ipify_ip

gives

shell> ansible-playbook -i hosts playbook.yml

PLAY [host01] *******************************

TASK [set_fact] *****************************
ok: [host01]

TASK [debug] ********************************
ok: [host01] =>
  ipify_ip: 1.2.3.4

TASK [debug] ********************************
ok: [host01] =>
  external_ip: 1.2.3.4

TASK [debug] ********************************
ok: [host01] =>
  msg: 1.2.3.4 is equal to 1.2.3.4

PLAY RECAP **********************************
host01: ok=4 changed=0 unreachable=0 failed=0 ...
Related