DEV Community

Mayeu
Mayeu

Posted on • Originally published at mayeu.me on

5

How to Read the Content of an External File With Ansible

Do you want to load up JSON data from a file directly into your Ansible playbook, tasks or roles? Did you start by trying to read it via a shell or command module and wondered if there was a better way? Well, there is, in the form or lookup plugins. Read on to see how to use it.

Ansible comes with a whole bunch of Lookup plugins that allow loading stuff from the outside your play. The one we are interested in today is thefile one. So, how do I load the content of my file with this?

Simply enough:

vars:
  file_contents: "{{lookup('file', 'path/to/file.json')}}"

And bam, you have the content in the file_contents variable!

As you see, we are calling the lookup() function, to which we are passing the plugin we want to use has the first argument (in that case file), and then the path to our file. And just with that we loaded our file content!

Note that the file must be on your Ansible controller (i.e.: the computer where you are running the ansible command).

You can directly use this in any module without the need for an intermediate variable:

- name: Read the content of a file instead of copying it directly
  copy:
    content: "{{lookup('file', 'path/to/file.json')}}"
    dest: /etc/config/file.json

And voilà 🙂

This post was originally published on my website: mayeu.me.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

Try REST API Generation for MS SQL Server.

DevOps for Private APIs. With DreamFactory API Generation, you get:

  • Auto-generated live APIs mapped from database schema
  • Interactive Swagger API documentation
  • Scripting engine to customize your API
  • Built-in role-based access control

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay