0
votes

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

Goal: I would like to gather information from various commands and save the result

My Playbook looks like this:

- name: Find the process
  shell: ps auxk +rss | tail
  register: process_name

- name: Check system activity
  shell: sar -W
  register: sar_output

- name: Run smem
  command: smem -s swap
  when:
    - ansible_facts['distribution'] == "RedHat"
    - ansible_facts['distribution_major_version'] == "7"
  register: smem_usage
  ignore_errors: yes

- name: Save content to a file
  local_action: copy content="{{ item }}" dest="/tmp/swap_info.txt"
  with_items:
    - "{{ process_name }}"
    - "{{ sar_output }}"
    - "{{ smem_usage }}"

But the /tmp/swap_info.txt contains only the last registered variable i.e - smem_usage info.

2
you can create a list of all the vars you want to save with a looped set_fact task, then run the copy module - ilias-sp

2 Answers

0
votes

An option would be to use template

- template:
    src: swap_info.txt.j2
    dest: /tmp/swap_info.txt

.

# cat swap_info.txt.j2
{{ process_name }}
{{ sar_output }}
{{ smem_usage }}
0
votes

Lineinfile module can do it:

---
- hosts: localhost
  tasks:
  - name: Test
    lineinfile:
      path: ./test.txt
      line: "Hello {{ item }}"
      create: true
    with_items:
      - "Test 1"
      - "Test 2"
      - "Test 3"