3

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?

1 Answer 1

4
- 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 }}"
2
  • That's awesome. In addition for optimization code. How can i save only if result of the task is successful? Example - I want to save "lspcideb" variable values only if ansible_os_family == "Debian"? and save "lspciredhat" values only if ansible_os_family == "RedHat"?
    – kurgulus
    Mar 22, 2017 at 5:43
  • You should be able to use default(omit) filter: {{ vars[item] | default(omit) }} to achieve what you want.
    – techraf
    Mar 22, 2017 at 5:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.