Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible - Retry task until a file contains a log line

I have an executable, lets say /tmp/foo

I want to try to run (5 times at most) this binary file until I see a line in a log file: lets say /tmp/start.log

I need such kind of a play:

- block:
    - shell: /tmp/foo

    - pause: seconds=30

    - name: Check if started successfully
      shell: grep 'started successfully' /tmp/start.log
      register: grep
  retry: 5
  until: grep.stdout 

But unfortunately Ansible block does not support retry-until.

How can I achieve this?

like image 505
turkenh Avatar asked Feb 06 '23 05:02

turkenh


2 Answers

I'd shot with single command:

- shell: /tmp/foo; sleep 30; grep 'started successfully' /tmp/start.log
  register: cmd_result
  retries: 5
  until: cmd_result | success
like image 95
Konstantin Suvorov Avatar answered Feb 24 '23 06:02

Konstantin Suvorov


For this case using a plain shell script should be the easiest method.

Shell script start_foo.sh (depending on the /tmp/foo exit code you might control if and where the script should fail with set -e and set +e):

#!/bin/sh
set -e    # fail the script if the command fails
/tmp/foo
sleep 30
set +e    # do not fail the script when string is not found
grep 'started successfully' /tmp/start.log
exit 0

Ansible task:

- script: start_foo.sh
  register: grep
  retry: 5
  until: grep.stdout 
like image 30
techraf Avatar answered Feb 24 '23 07:02

techraf