Skip to content
Advertisement

Iterating Ansible setup command

I want to use ansible setup module to retrieve hosts specs and I tried with a bash for loop.

Ansible version: 2.4

My hosts inventory has been defined in a group of machines which I called rhelmachines

I would like to collect the following list of variables called “specs”

declare -a specs=("ansible_all_ipv4_addresses" "ansible_processor" "ansible_processor_cores" "ansible_uptime_seconds")

I am then trying to include the ansible command in a for bash loop:

for i in "${specs[@]}"
do
    ansible rhelmachines -m setup -a 'filter='$i'
done

how can I concatenate multiple filters in one connection only ?

Thanks!

Advertisement

Answer

As one of the possible solution, I implemented an Ansible code exploiting Ansible facts. I implemented it first gathering the ansible facts. Then, I used a local_action and a loop. The loop indices are the several ansible facts. For every fact I am writing out a line of a file. In this way I am getting a file composed by all the ansible facts I declared in the loop for the rhelmachines.

---
- hosts: rhelmachines
  gather_facts: True
  tasks:
  - name: Gather Facts
    setup:
        gather_subset=all
    register: facts

  - debug:
      msg: "{{ facts.ansible_facts.ansible_all_ipv4_addresses }}"

  - name: copy content from facts to output file
    local_action:
     module: lineinfile
     line: "{{ item }}"
     path: /tmp/assessments/facts.txt
    loop:
      - "{{ facts.ansible_facts.ansible_all_ipv4_addresses }}"
      - "{{ facts.ansible_facts.ansible_all_ipv6_addresses }}"
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement