Bootstrap FreeKB - Ansible - Write to a local file using the shell module
Ansible - Write to a local file using the shell module

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter 3882f9 in the box below so that we can be sure you are a human.