Ansible - Write to a local file using the shell module
by
Jeremy Canfield |
Updated: August 18 2022
| Ansible articles
If you are not familiar with modules, check out Ansible - Getting Started with Modules.
In this example, "Hello World" is written to foo.txt.
- name: "write local file"
shell: "echo 'Hello World' > /tmp/foo.txt"
delegate_to: "localhost"
The lookup plugin and vars plugin the can be used to store the content of the file in a variable.
vars:
foo: "{{ lookup('file', '/tmp/foo.txt') }}"
Likewise, the set_fact module can be used to store the content of the file in a variable.
- name: "store the content of foo.txt in the foo variable"
set_fact:
foo: "{{ lookup('file', 'foo.txt') }}"
The debug module can be used to print the contents of the file. Notice the double curley braces {{ ... }}. Jinja2 uses double curley braces for variables.
- name: "display the contents of the 'foo' variable"
debug:
msg: "{{ foo }}"
Running this play should return the following.
TASK [display the contents of the 'foo' variable]
ok: [localhost] => {
"msg": "Hello World"
}
Did you find this article helpful?
If so, consider buying me a coffee over at