append to a list with variables of hosts that failed

148 views
Skip to first unread message

Jay Kumar

unread,
Feb 17, 2023, 11:08:15 PM2/17/23
to Ansible Project
Hello,
 I tried to initialize a list and attach it to local host. I want to add to the list across plays so that the hostname of each host that failed is added to list but it seems that this does not work new list = old list + new hostname of host that failed. Even if there are 3 hosts that failed the list at the end of the play only contains one host. Here is my script, the list is called continents.

---
- name: Create a array that persists across plays
  hosts: localhost
  gather_facts: no
 
  tasks:
    - name: create an array
      set_fact:
        continents: []

- name: see if array persists persists
  hosts: all
  become: yes
  gather_facts: no

  tasks:
    - name: Get hostname
      shell: |
        hostname -f
      register: host

    - name: set a global variable
      set_fact: my_global_var={{ host.stdout }}

    - name: debug2
      debug: var=my_global_var
   
    - name: pre array
      debug: var=hostvars['localhost'].continents

    - block:
      - name: invoke tasks that wil cause at least 2 hosts to fail
        include_tasks: task.yml
        vars:
          nr: 10
          n1: 10
     
      rescue:
      - name: list hostnames that failed
        debug:
          var: hostvars[inventory_hostname].my_global_var
       
      - name: append to list 
        set_fact:
          continents: "{{  hostvars['localhost'].continents + [ my_hostname_var ] }}"
        delegate_to: localhost
        delegate_facts: true
       
    - name: post array
      debug: var=hostvars['localhost'].continents

arr.PNG

Thank you in advance.
Reply all
Reply to author
Forward
0 new messages