Ansible slurp - ghdrako/doc_snipets GitHub Wiki

http://www.freekb.net/Article?id=2389

both slurp and fetch and both mention they are intended to get the remote file.

The slurp module can be used the read the content of a file on a managed node (e.g. target system). However, when you want to read a file on the control node, the more common approach is to use the lookup plugin.

- name: Load spark defaults
  slurp:
    src: /etc/spark/conf/spark-defaults.conf
  delegate_to: my.host
  remote_user: me
  register: spark_defaults

use the stat module to determine if the file exists and is readable.

- name: store the stats of /tmp/foo.txt in the 'foo' variable
  stat:
    path: /tmp/foo.txt
  register: foo

Surp module is used to get the content of foo.txt, and the register parameter stores the content in the "out" variable.

- name: read /tmp/foo.txt
  slurp:
    src: /tmp/foo.txt
  register: out
  when:
    - foo.stat.exists == true
    - foo.stat.readable == true

"content" is "bmV3IGxpbmUK" and encoding is "base64".

- name: output the content of the 'out' variable
  debug:
    var: out

to display the content of the file, the b64decode filter can be used.

- debug:
    msg: "{{ out['content'] | b64decode }}"

use the set_fact module to create a new variable that contains the content of the file

- set_fact:
    content: "{{ out['content'] | b64decode }}"

If you want to display the content of the file, you would do something like this.

- debug:
    var: content

Split new lines (\n)

split can be used to split the new lines.

- set_fact:
    content: "{{ out['content'] | b64decode }}"

- set_fact:
    lines: "{{ content.split('\n') }}"

The debug module can be used to print the output.

- debug:
    var: line_one

Determine if file does or does not contain a certain string

The following can be used to determine if foo.txt contains the string "Hello World".

- name: read foo.txt
  slurp:
    src: foo.txt
  register: out

- set_fact:
    content: "{{ out['content'] | b64decode }}"

- name: foo.txt contains Hello World
  debug:
    msg: foo.txt contains Hello World
  when: content is search 'Hello World'

- name: foo.txt does not contain Hello World
  debug:
    msg: foo.txt does not contain Hello World
  when: content is not search 'Hello World'

regex_search

regex_search or regex_findall can be used to only return lines in the file that contain a certain string.

- debug:
    msg: "{{ out['content'] | b64decode | regex_findall('.*Line 2.*') }}"

Which should now return the following.

TASK [debug]
ok: [server1.example.com] => {
    "msg": "Line 2"
}