Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 802
Maximilian Kindshofer Avatar asked Nov 04 '14 09:11

Maximilian Kindshofer


People also ask

What does Set_fact do in Ansible?

This module allows setting new variables. Variables are set on a host-by-host basis just like facts discovered by the setup module. These variables will be available to subsequent plays during an ansible-playbook run.


2 Answers

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 
like image 78
Ramon de la Fuente Avatar answered Sep 21 '22 06:09

Ramon de la Fuente


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" 
like image 24
Umesh Tyagi Avatar answered Sep 19 '22 06:09

Umesh Tyagi