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?

Community
  • 1
  • 1
kurgulus
  • 75
  • 1
  • 2
  • 7

1 Answers1

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 }}"
techraf
  • 64,883
  • 27
  • 193
  • 198
  • 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 '17 at 05:43
  • You should be able to use `default(omit)` filter: `{{ vars[item] | default(omit) }}` to achieve what you want. – techraf Mar 22 '17 at 05:49