Ansible: creating a variable from a remote or local file content

With Ansible, it is possible to have a variable populated with either the content of a remote or local file.

For a file on a remote host, you can use the ‘slurp‘ module to put the content into a register, but then you must base64 decode the content.

- name: get content of remote file
  slurp:
    src: "{{remote_path}}"
  register: remote_content_encoded

- name: decode remote content
  set_fact:
    remote_content: "{{remote_content_encoded.content | b64decode}}"

- debug:
    msg: "content of remote file {{remote_path}}: {{remote_content}}"

For a file on the local Ansible orchestrator host, you can use the file lookup plugin to get the content combined with set_fact.

- name: get content of local file
  set_fact:
    readme_contents: "{{ lookup('file',playbook_dir + '/' + local_path) }}"

- debug:
    msg: "content of local file {{local_path}}: {{readme_contents}}"

I have provided a sample playbook, playbook-local-remote-content.yaml

REFERENCES

ansible, slurp module

ansible, lookup plugin