ansible: run task multiple times on the same host

Viewed 728

I need to run the same task 48 times under a block.

I did not find any information on how to do this. I need it to run under a block, because if it fails it will continue until it reaches 48 times. I would appreciate any information or suggestion on how to do this in the most correct way.

This is my code:

---
  - name: Playbook for productaion - Exmpale
    hosts: dev
    become: true
    become_user: root

    tasks:   
      - name: Checking Performance test under block 48 times
        block:
          - name: Runing Performance Test
            shell: nohup /root/test/run_pf_new.py &
            args:
              chdir: /root/test/
          - name: Checking Performance Test
            shell: /root/test/checking_pf_new.py > /root/test/out8 2>&1; cat /root/test/out8 | grep -iw 'ok' > /dev/null; if [ $? == 0 ]; then echo 'pass'; else echo 'fail'; fi    
            args:
              chdir: /root/test/
            async: 3600
            poll: 1
            register: pf
          - debug: msg="Performance testing was successful"
            when: pf.stdout == "pass"
        - name: Reboot after removing the windows boot
          reboot:
            reboot_timeout: 600
          when: pf.stdout == "pass"
          - debug:
                msg: "Performance test failed"
            when: pf.stdout == "fail"
            failed_when: pf.stdout == "fail"
        rescue:
          - debug:
                msg: 'I caught an error under performance testing'
1 Answers

An option would be to include tasks in a loop with range. For example, given the simplified scripts

shell> cat /root/test/perf-test.sh
#!/bin/bash
exit 0
shell> cat /root/test/perf-test-check.sh
#!/bin/bash
rand=$((RANDOM%10))
if (( rand > 5 )); then
    echo pass
    exit 0
else
    echo fail
    exit 1
fi

the simplified block

shell> cat perf-test.yml
- name: Performance test
  block:
    - name: Runing Performance Test
      shell: /root/test/perf-test.sh
    - name: Checking Performance Test
      shell: /root/test/perf-test-check.sh
    - debug:
        msg: "[{{ item }}] [OK]  Performance test passed."
  rescue:
    - debug:
        msg: "[{{ item }}] [ERR] Performance test failed."

and the playbook

shell> cat playbook.yml
- hosts: localhost
  become: true
  tasks:
    - include_tasks: perf-test.yml
      loop: "{{ range(stop|d(3)|int) }}"

give

shell> ansible-playbook playbook.yml -e stop=10 | grep msg: | grep test
  msg: '[0] [OK]  Performance test passed.'
  msg: '[1] [OK]  Performance test passed.'
  msg: '[2] [ERR] Performance test failed.'
  msg: '[3] [ERR] Performance test failed.'
  msg: '[4] [ERR] Performance test failed.'
  msg: '[5] [ERR] Performance test failed.'
  msg: '[6] [ERR] Performance test failed.'
  msg: '[7] [OK]  Performance test passed.'
  msg: '[8] [ERR] Performance test failed.'
  msg: '[9] [ERR] Performance test failed.'
Related