Ansible - shell module (write local file)

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.

  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"
    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"
    msg: "{{ foo }}"


Running this play should return the following.

TASK [display the contents of the 'foo' variable]
ok: [localhost] => {
    "msg": "Hello World"


Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

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


Web design by yours truely - me, myself, and I   |   |