Ansible: Save registered variables to file

ansible

How could I save a registered variables to a file using Ansible?

Goal:

  1. 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).
  2. 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?

Best Answer

- name: copy content
  local_action: copy content="{{ vars[item] }}" dest="/path/to/destination/file-{{ item }}-{{ ansible_date_time.date }}-{{ ansible_hostname }}.log"
  with_items:
    - lspcideb
    - aptlist
    - lspciredhat

Explanation:

You must embed variable names in Jinja2 expressions to refer to their values, otherwise you are passing strings. So:

with_items:
  - "{{ lspcideb }}"
  - "{{ aptlist }}"
  - "{{ lspciredhat }}"

It's a universal rule in Ansible. For the same reason you used {{ item }} not item, and {{ foo_result }} not foo_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:

- name: copy content
  local_action: copy content="{{ item.value }}" dest="/path/to/destination/file-{{ item.variable }}-{{ ansible_date_time.date }}-{{ ansible_hostname }}.log"
  with_items:
    - variable: lspcideb
      value: "{{ lspcideb }}"
    - variable: aptlist
      value: "{{ aptlist }}"
    - variable: lspciredhat 
      value: "{{ lspciredhat }}"