Skip to main content

Inventory from gathered facts.

Playbook example

---
- name: Generate YAML Inventory File from Gathered Facts
  hosts: all
  gather_facts: true
  tasks:
    - name: Gather facts from hosts
      setup:

    - name: Create YAML inventory file
      copy:
        content: |
          all:
            children:
              hosts:
                hosts:
          {{ hostvars[item].inventory_hostname }}:
            ansible_host: {{ hostvars[item].ansible_host }}
            ansible_user: {{ hostvars[item].ansible_user }}
            ansible_port: {{ hostvars[item].ansible_port }}
            ansible_ssh_pass: {{ hostvars[item].ansible_ssh_pass | default('') }}
            ansible_ssh_private_key_file: {{ hostvars[item].ansible_ssh_private_key_file | default('') }}
          inventory_hostname: {{ hostvars[item].inventory_hostname }}
        dest: /path/to/your/output/inventory.yaml
        mode: 0644
      loop: "{{ ansible_play_batch }}"
      run_once: yes

We define a play named "Generate YAML Inventory File from Gathered Facts" that runs on all hosts (hosts: all) and enables fact gathering with gather_facts: true.

In the first task, we use the setup module to gather facts from the hosts.

In the second task, we use the copy module to create the YAML inventory file. We loop through each host in ansible_play_batch (which contains all the hosts that ran this play) and format the gathered facts into the inventory file.

    ansible_host, ansible_user, ansible_port, ansible_ssh_pass, ansible_ssh_private_key_file, and inventory_hostname are some of the facts we include in the inventory file.

    The inventory file is saved at the specified destination path (/path/to/your/output/inventory.yaml) with appropriate file permissions (mode 0644).

Make sure to replace /path/to/your/output/inventory.yaml with the actual path where you want to save the generated YAML inventory file.

You can run this playbook with the ansible-playbook command: