4

With Ansible, I need to extract content from multiple files. With one file I used slurp and registered a variable.

- name: extract nameserver from .conf file
  slurp:
    src: /opt/test/roles/bind_testing/templates/zones/example_file.it.j2
  delegate_to: 127.0.0.1
  register: file

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

But now I have multiple files so I need to extract content from every files, register them one by one to be able to process them later with operations like sed, merging_list etc...

How can I do this in ansible?

I tried to use slurp with with_fileglob directive but I couldn't register the files...

- name: extract nameserver from .conf file
  slurp:
    src: "{{ item }}"
  with_fileglob:
    - "/opt/test/roles/bind9_domain/templates/zones/*"
  delegate_to: 127.0.0.1
  register: file

2 Answers 2

6

You should just use the loop option, configured with the list of files to slurp. Check this example:

---
- hosts: local
  connection: local
  gather_facts: no
  tasks:
    - name: Find out what the remote machine's mounts are
      slurp:
        src: '{{ item }}'
      register: files
      loop:
        - ./files/example.json
        - ./files/op_content.json

    - debug:
        msg: "{{ item['content'] | b64decode }}"
      loop: '{{ files["results"] }}'

I am slurping each file, and then iterating through the results to get its content.

I hope it helps.

3
  • Thanks for answer, but i have 78 files in the dir, so: loop: - /my_dir/files1 - /my_dir/files2 ...... - /my_dir/files78 I don't want to list them all
    – Luca
    Commented Jul 31, 2019 at 15:07
  • Then add a task on top to list the files and create the list programmatically. For example, take a look at the file module to do that.
    – guzmonne
    Commented Jul 31, 2019 at 15:11
  • This just leads to an exception in Ansible... "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'content'"
    – Halsafar
    Commented Oct 9, 2019 at 17:14
0

If you're looking for a host's mounts you could utilize ansible_facts.

    "ansible_mounts": example:

- name: Free-space.yml Date
  command: date

- name: Display more vars
  debug:
    msg:
    - "Variable list"
    - "diskfree_req is:  '{{diskfree_req}}' "
    - "mountname is:     '{{mountname}}' "

- name: PreTest for freespace
  vars: 
    deprecation_warnings: False
    #mountname: '/opt/oracle'
    mount: "{{ ansible_mounts | selectattr('mount','equalto', mountname) | first }}"

  assert:
    that: mount.size_available > {{diskfree_req}}
    msg: 
    - "DANGER : disk space is low"
    - "'{{mountname}} only has {{mount.size_available}} available. Please correct"
  register: disk_free

Not the answer you're looking for? Browse other questions tagged or ask your own question.