Monday, August 14, 2017

Looping in ansible

If you have defined a YAML list in a variables file, or the ‘vars’ section, you can also do:
with_items: "{{ somelist }}"

Looping over file

---
 - hosts: ss
   tasks:
   - name: check the contents of a file and echo it
     debug: msg="{{item}}"
     with_file:
      - /home/bhr_moham607/test1.txt
      - /home/bhr_moham607/test2.txt

will loop and echo the message if only both the files are available. Also these files should be in master

Looping with Fileglob

with_fileglob matches all files in a single directory, non-recursively, that match a pattern. It calls Python’s glob library, and can be used like this:

---
- hosts: all
  tasks:
    # first ensure our target directory exists
    - name: Ensure target directory exists
      file:
        dest: "/etc/fooapp"
        state: directory

    # copy each file over that matches the given pattern
    - name: Copy each file over that matches the given pattern
       copy:
        src: "{{ item }}"
        dest: "/etc/fooapp/"
        owner: "root"
        mode: 0600
        with_fileglob:
         - "/playbooks/files/fooapp/*"

No comments:

Post a Comment