Venu S
Venu S

Reputation: 3681

Ansible files lookup in directory remote hosts

I am trying to execute the scripts from a directory in a particular order with an interval of 90 sec each iteration. For instance, I want to to start the scripts under /opt/scripts/, and it has (SK-1.sh, SK-2.sh, PX.sh, N1.sh,N2.sh). I want to start scripts that are SK and then PX and finally N.

- name: execute scripts A
shell: "ls -ltr {{ item }}"
args:
  chdir: "/opt/scripts/"
with_fileglob:
- "/opt/scripts/*SK*.sh"
- "/opt/scripts/*PX*.sh"
- "/opt/scripts/*N*.sh"
loop_control:
  pause: 90

But fileglob will look up for those scripts only on the controller host (Ansible tower), hence not working. Is there some kind of filter I can use that would work on remote hosts rather controller host ?

I am trying to avoid the listing of the files from a previous task and register the items to process. After all that is becoming a two step task.

Upvotes: 0

Views: 1356

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 67959

Q: "Start scripts that are SK and then PX and finally N."

A: The Ansible module find neither keeps the order of the patterns nor sorts the results. You'll have to iterate the list of the globs on your own and sort the results to achieve the required order. For example, create a file with the tasks

shell> cat find_and_execute.yml
- find:
    paths: /tmp
    patterns: "{{ eitem }}"
  register: result
- debug:
    msg: "{{ '%H:%M:%S'|strftime }} Execute {{ item }}"
  loop: "{{ result.files|map(attribute='path')|list|sort }}"
  loop_control:
    pause: 3

and use it in a playbook. For example

shell> cat pb.yml
- hosts: test_11
  tasks:
    - include_tasks: find_and_execute.yml
      loop:
        - 'SK*.sh'
        - 'PX*.sh'
        - 'N*.sh'
      loop_control:
        loop_var: eitem

gives

  msg: 18:19:14 Execute /tmp/SK-1.sh
  msg: 18:19:17 Execute /tmp/SK-2.sh
  msg: 18:19:21 Execute /tmp/PX.sh
  msg: 18:19:24 Execute /tmp/N1.sh
  msg: 18:19:27 Execute /tmp/N2.sh

Fit the parameters to your needs.


    - find:
        paths: /tmp
        patterns:
          - 'SK*.sh'
          - 'PX*.sh'
          - 'N*.sh'
      register: result
    - debug:
        msg: "{{ result.files|map(attribute='path')|list }}"

give

  msg:
  - /tmp/SK-2.sh
  - /tmp/SK-1.sh
  - /tmp/N2.sh
  - /tmp/N1.sh
  - /tmp/PX.sh

Upvotes: 2

Related Questions