Using facts with Ansible Tower does not appear to work

Hi,

I’ve been trying to get Ansible Tower to run a playbook/role which should update the /etc/hosts file across all hosts in a group.

I have the following playbook:

  • name: Update hosts file if required
    hosts: all
    gather_facts: yes

roles:

  • { role: hostfile }

and the following role:

I've been trying to get Ansible Tower to run a playbook/role which should
update the /etc/hosts file across all hosts in a group.

I have the following playbook:

- name: Update hosts file if required
  hosts: all
  gather_facts: yes

  roles:
    - { role: hostfile }

and the following role:

---

- debug: var=ansible_default_ipv4.address

- name: node to ip mapping
  debug: var=hostvars[item].ansible_default_ipv4.address
  with_items: groups['all']

It you check your output you will see that your item i literally the string groups['all']. But you need to write this as a variable
   with_items: "{{ groups['all'] }}"

- name: Build Host file
  lineinfile: dest=/etc/hosts
              regex='.*{{ item }}$ }}'
              line="{{ hostvars[item].ansible_default_ipv4.address }}
{{item}}"
              state=present
  when: hostvars[item].ansible_default_ipv4.address is defined
  with_items: groups['all']
  become: true

However, when Tower run this its skips the 2 hosts in the group. From
looking at the debug output it would appear that Tower is not caching the
facts under hostvars as you can see from the output below:

TASK [setup]
******************************************************************* ok:
[172.31.9.43] ok: [52.50.60.2] TASK [hostfile : debug]
******************************************************** ok: [172.31.9.43]
=> { "ansible_default_ipv4.address": "172.31.9.43" } ok: [52.50.60.2] => {
"ansible_default_ipv4.address": "172.31.33.206" } TASK [hostfile : node to
ip mapping] ******************************************* ok: [172.31.9.43]
=> (item=groups['all']) => { "hostvars[item].ansible_default_ipv4.address":

Here you see your item is "groups['all']" and not a hostname.

I have a feeling that I'm missing something very obvious here. Any ideas
where I should look?

Bare variables in with_items was deprecated before 2.2, in 2.2 it will take a bare variable as a string.

Hi,

Many thanks for that, hoped it was straight forward.

All working now.

Many thanks,
Jon