How could I save a registered variables to a file using Ansible?
Goal:
- I would like to gather detailed information about all PCI buses and devices in the system and save the result somewhere (Ex. using lspci. Ideally, I should have results of command in my local machine for further analysis).
- Save results also somewhere with the given criterion.
My playbook looks like this:
tasks: - name: lspci Debian command: /usr/bin/lspci when: ansible_os_family == "Debian" register: lspcideb - name: lspci RedHat command: /usr/sbin/lspci when: ansible_os_family == "RedHat" register: lspciredhat - name: copy content local_action: copy content="{{ item }}" dest="/path/to/destination/file-{{ item }}-{{ ansible_date_time.date }}-{{ ansible_hostname }}.log" with_items: - lspcideb - aptlist - lspciredhat
But saves only item_name
Good Q&A with saving 1 variable there - Ansible - Save registered variable to file.
- local_action: copy content={{ foo_result }} dest=/path/to/destination/file
My question:
How can I save multiple variables and transfer stdout to my local machine?
Explanation:
You must embed variable names in Jinja2 expressions to refer to their values, otherwise you are passing strings. So:
It's a universal rule in Ansible. For the same reason you used
{{ item }}
notitem
, and{{ foo_result }}
notfoo_result
.But you use
{{ item }}
also for the file name and this will likely cause a mess.So you can refer to the variable value with:
{{ vars[item] }}
.Another method would be to define a dictionary: