Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: simulating a "passed when" module

Ansible provides a failed_when module, allowing users to specify certain fail conditions on their tasks, e.g. a certain string being found in stdout or stderr.

I am trying to do the opposite: I'd like my tasks not to fail if any of a set of strings is found in stdout or stderr. In other words, I'd like something approaching the functionality of a passed_when module.

  • I still want it to pass normally when the return code is 0.
  • But if it would fail (rc != 0) then it should first check for the occurrence of some string.
  • I.e. if some string is found it passes no matter what.

My reasoning goes like this:

There are many reasons why the task could fail - but some of these, depending on the output, I do not consider as a failure in the current context.

Does anybody have a good idea how this can be achieved?

like image 605
fgysin Avatar asked Jan 08 '15 08:01

fgysin


2 Answers

Have a look here:

Is there some Ansible equivalent to "failed_when" for success

- name: ping pong redis
  command: redis-cli ping
  register: command_result
  failed_when: 
    - "'PONG' not in command_result.stderr"
    - "command_result.rc != 0"
  • will not fail if return code is 0 and there is no 'PONG' in stderr.
  • will not fail if there is "PONG" in stderr.

So it passes if any of the list is False

like image 76
ProfHase85 Avatar answered Nov 17 '22 16:11

ProfHase85


Your original question was phrased like this (using boolean logic to make it easier):

Succeed a command if a set of strings is found in stdout or stderr

Rephrasing your logic:

fail if a set of strings is NOT found in stdout or stderr. Using this logic it's easy to do with failed_when. Here's a snippet:

---
- name: Test failed_when as succeed_if
  hosts: localhost
  connection: local
  gather_facts: no

  tasks:
    - name: "'succeed_if' set of strings in stdout"
      command: /bin/echo succeed1
      register: command_result
      failed_when: "command_result.stdout not in ['succeed1',]"

    - name: "'succeed_if' set of strings in stdout (multiple values)"
      command: /bin/echo succeed2
      register: command_result
      failed_when: "command_result.stdout not in ['succeed1', 'succeed2']"

    - name: "'succeed_if' set of strings in stderr (multiple values)"
      shell: ">&2 /bin/echo succeed2 "
      register: command_result
      failed_when: "command_result.stderr not in ['succeed1', 'succeed2']"

    - name: "'succeed_if' set of strings in stderr (multiple values) or rc != 0"
      shell: ">&2 /bin/echo succeed2; /bin/false"
      register: command_result
      failed_when: "command_result.stderr not in ['succeed1', 'succeed2'] and command_result.rc != 0"

# vim: set ts=2 sts=2 fenc=utf-8 expandtab list:

Also the documenation you are probably looking for are Jinja2 Expressions

like image 39
Martin M. Avatar answered Nov 17 '22 16:11

Martin M.