Ansible - Save registered variable to file


How would I save a registered Variable to a file? I took this from the tutorial:

- hosts: web_servers


     - 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?

This question is tagged with ansible ansible-playbook

~ Asked on 2014-11-04 09:58:23

The Best Answer is


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: Write variable to a file in Ansible

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

~ Answered on 2014-11-04 12:48:08


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"

~ Answered on 2016-05-04 21:14:44

Most Viewed Questions: