Search code examples
ansibleansible-inventory

Ansible. Dynamically add hostname variable


I have a yaml Ansible inventory with structure like below

rpi_wifi:
  children:
    _wifi:
      hosts:
        10.74.47.49 :
        10.74.47.218:
        10.74.47.70 :

My goal is to have a playbook that will gather ansible_hostname var from each host and will add it to the new line for each host in the inventory file So i created something like this

- name: Add ansible_hostname to hosts
  hosts: rpi_wifi
  gather_facts: true
  tasks:
    - name: Update inventory file with ansible_hostname_var
      lineinfile:
        path: hosts0.yml
        regexp: "{{ inventory_hostname }}"   
        line: "{{ ansible_hostname }}                   \n {{ ansible_hostname }}"
      delegate_to: localhost

So the final result should be like below

rpi_wifi:
  children:
    _wifi:
      hosts:
        10.74.47.49 :
          ansible_hostname: foo
        10.74.47.218:
          ansible_hostname: bar
        10.74.47.70 :
          ansible_hostname: foo-bar

At this moment, my main issue is that for some reason, Ansible isn't adding a hostname for each host. It can skip one or more of them, and it happens randomly on every run. I can't understand why, despite this when I'm running it with -vvv option it shows that it has gathered the hostname correctly

The second issue is tabulation in YAML format. My inventory is in yaml format, so i need to have various counts of spaces for my host groups, is there any other way to handle it ?


Solution

  • It works with this code

    - name: Update inventory file with ansible_hostname_var
      throttle: 1
      lineinfile:
        backrefs: true
        path: hosts0.yml
        regexp: '^(\s*)({{ inventory_hostname }}:)'
        line: '\1\2\n\1  hostname: "{{ ansible_hostname }}"'
      delegate_to: localhost