Wednesday, February 7, 2024

[SOLVED] saving variables from playbook run to ansible host local file

Issue

I'm sort of trying to build an inventory file from an ansible playbook run. I'm trying to list out all the kvm hosts and the guests running on them, by running both service libvirtd status and if successful, virsh list --all, and to store the values in a file on the ansible host. Ive tried a few different playbook structures but none have been successful in writing the file (using local_action wrote the ansible_hostname from just one host). Please can someone guide me on what I'm doing wrong? This is what I'm running:

- name: Determine KVM hosts
  hosts: all
  become: yes
  #gather_facts: false

  tasks:
    - name: Check if libvirtd service exists
      shell: "service libvirtd status"
      register: libvirtd_status
      failed_when: not(libvirtd_status.rc == 0)
      ignore_errors: true

    - name: List KVM guests
      shell: "virsh list --all"
      register: list_vms
      when: libvirtd_status.rc == 0
      ignore_errors: true

    - name: Write hostname to file
      lineinfile:
        path: /tmp/libvirtd_hosts
        line: "{{ ansible_hostname }} kvm guests: "
        create: true
    #local_action: copy content="{{ item.value }}" dest="/tmp/libvirtd_hosts"
      with_items:
          - variable: ansible_hostname
            value: "{{ ansible_hostname }}"
          - variable: list_vms
            value: "{{ list_vms }}"
      when: libvirtd_status.rc == 0 or list_vms.rc == 0

Solution

Was able to cobble something that's mostly working:

- name: Check if libvirtd service exists
      shell: "service libvirtd status"
      register: libvirtd_status
      failed_when: libvirtd_status.rc not in [0, 1]

    - name: List KVM guests
      #shell: "virsh list --all"
      virt:
        command: list_vms
      register: all_vms
      when: libvirtd_status.rc == 0
---
- name: List all KVM hosts
  hosts: production, admin_hosts, kvm_hosts
  become: yes

  tasks:
    - name: create file
      file:
          dest: /tmp/libvirtd_hosts
          state: touch
      delegate_to: localhost

    - name: Copy VMs list
      include_tasks: run_libvirtd_commands.yaml

    - name: saving cumulative result
      lineinfile:
         line: '{{ ansible_hostname }} has {{ all_vms }}'
         dest: /tmp/libvirtd_hosts
         insertafter: EOF
      delegate_to: localhost
      when: groups["list_vms"] is defined and (groups["list_vms"] | length > 0)

Now if only I could clean up the output to filter out false positives (machines that don't have libvirtd status, and have an empty/no list of VMs, because the above doesn't really work.

But at least there is output from all the KVM hosts!



Answered By - Unpossible
Answer Checked By - Robin (WPSolving Admin)