I see there is a lot to learn and understand yet (in this case "use
of variables" for example).
> > - hosts: all
> > vars:
> > ansible_user: gwagner
> > ver: "{{ ansible_play_hosts|
> > map('extract', hostvars, ['backrest_version', 'stdout'])|
> > map('split', ' ')|map('last')|
> > list }}"
> > pkg: "{{ dict(ansible_play_hosts|zip(ver)) }}"
> >
> > tasks:
> > - name: check pgBackRest version
> > ansible.builtin.command: /usr/bin/pgbackrest version
> > register: backrest_version
> >
> > - name: Print return information from the previous task
> > ansible.builtin.debug:
> > var: backrest_version.stdout
> > when: debug|d(false)|bool
> >
> > - name: Write the CSV file
> > ansible.builtin.copy:
> > dest: pkg.csv
> > content: |-
> > {% for k,v in pkg.items() %}
> > {{ k }},{{ v }}
> > {% endfor %}
> > delegate_to: localhost
> > run_once: true
There are a couple of aspects.
* It's good to know that in Ansible the variables are evaluated at
the last moment, aka "lazy evaluation".
* There are many places where you can declare variables. See
https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#variable-precedence-where-should-i-put-a-variable
* Where would you like to use the variables? In your case, this is
probably the best question to ask when you want to decide where to
declare the variables. Put them into the playbook vars (above) if
you want to use them in the whole playbook. If you need the
variables to write the CSV file only put them into the task vars
(below)
- name: Write the CSV file
ansible.builtin.copy:
dest: pkg.csv
content: |-
{% for k,v in pkg.items() %}
{{ k }},{{ v }}
{% endfor %}
delegate_to: localhost
run_once: true
vars:
ver: "{{ ansible_play_hosts|
map('extract', hostvars,
['backrest_version','stdout'])|map('split', ' ')|
map('last')|
list }}"
pkg: "{{ dict(ansible_play_hosts|zip(ver)) }}"
This limits the scope of the variables. See
https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#scoping-variables
* To make the code cleaner, you can put the variables into some files.
For example into the group_vars,
> cat group_vars/all
ansible_user: gwagner
ver: "{{ ansible_play_hosts|
map('extract', hostvars, ['backrest_version', 'stdout'])|
map('split', ' ')|map('last')|
list }}"
pkg: "{{ dict(ansible_play_hosts|zip(ver)) }}"
content: |-
{% for k,v in pkg.items() %}
{{ k }},{{ v }}
{% endfor %}
This will simplify the playbook
- hosts: all
tasks:
- name: check pgBackRest version
ansible.builtin.command: /usr/bin/pgbackrest version
register: backrest_version
- name: Write the CSV file
ansible.builtin.copy:
dest: pkg.csv
content: "{{ content }}"
delegate_to: localhost
run_once: true