Ansible - Save registered variable to file
AnsibleAnsible PlaybookAnsible Problem Overview
How would I save a registered Variable to a file? I took this from the tutorial:
- hosts: web_servers
tasks:
- shell: /usr/bin/foo
register: foo_result
ignore_errors: True
- shell: /usr/bin/bar
when: foo_result.rc == 5
How would I save foo_result
variable to a file e.g. foo_result.log
using ansible?
Ansible Solutions
Solution 1 - Ansible
Thanks to tmoschou for adding this comment to an outdated accepted answer:
As of Ansible 2.10, The documentation for ansible.builtin.copy says:
If you need variable interpolation in copied files, use the
ansible.builtin.template module. Using a variable in the content field will
result in unpredictable output.
For more details see this and an explanation
Original answer:
You can use the copy
module, with the parameter content=
.
I gave the exact same answer here: https://stackoverflow.com/questions/26638180/write-variable-to-a-file-in-ansible/26640778#26640778
In your case, it looks like you want this variable written to a local logfile, so you could combine it with the local_action
notation:
- local_action: copy content={{ foo_result }} dest=/path/to/destination/file
Solution 2 - Ansible
I am using Ansible 1.9.4 and this is what worked for me -
- local_action: copy content="{{ foo_result.stdout }}" dest="/path/to/destination/file"
Solution 3 - Ansible
More readable way of achieving this (not a fan of single line ansible tasks)
- local_action:
module: copy
content: "{{ foo_result }}"
dest: /path/to/destination/file
Solution 4 - Ansible
A local action will run once for each remote host (in parallel). If you want a unique file per host, make sure to put the inventory_hostname as part of the file name.
- local_action: copy content={{ foo_result }} dest=/path/to/destination/{{ inventory_hostname }}file
If you instead want a single file with all host's information, one way is to have a serial task (don't want to append in parallel) and then append to the file with a module (lineinfile is capable, or could pipe with a shell command)
- hosts: web_servers
serial: 1
tasks:
- local_action: lineinfile line={{ foo_result }} path=/path/to/destination/file
Alternatively, you can add a second play/role/task to the playbook which runs against only local host. Then access the variable from each of the hosts where the registration command ran inside a template Access Other Hosts Variables Docs Template Module Docs
Solution 5 - Ansible
---
- hosts: all
tasks:
- name: Gather Version
debug:
msg: "The server Operating system is {{ ansible_distribution }} {{ ansible_distribution_major_version }}"
- name: Write Version
local_action: shell echo "This is {{ ansible_distribution }} {{ ansible_distribution_major_version }}" >> /tmp/output