Run Ansible task conditionally and fail if condition is not met

Coder asked:

I am very new to Ansible and having an issue.
I want to run the module only if a condition is met but if the condition is failed, it should fail the task and report to user.
Currently what I have done, it will only skip it rather than failing it.

Below is my code, I have the when condition to check and only run if result.stdout == ‘valid’ but I want to fail the task if its ‘invalid’.Currently it just skips it if condition not met.

---
- name: Check Value
  become: yes
  shell: /usr/bin/python3 check.py
  args:
    chdir: "mydir/scripts/"
  register: result
  tags: data_merge

- name: Merge Data
  become: yes
  when: result.stdout == 'valid'
  local_action:
    module: some_module
    provider: "{{some_provider}}"
    role_path: "{{role_path}}"
  run_once: true
  tags: data_merge

My answer:


You should fail yourself explicitly in this scenario.

- name: Fail when value is not valid
  fail:
    msg: "A custom message to tell the user what went wrong"
  when: result.stdout != 'valid'

You can also simply check the result directly in the play which runs your check script.

- name: Check Value
  become: yes
  shell: /usr/bin/python3 check.py
  args:
    chdir: "mydir/scripts/"
  register: result
  tags: data_merge
  failed_when: "'invalid' in result.stdout"

You should consider using exit codes in your application to indicate success or failure, as most programs already do. This makes for a much more reliable check than checking for text on stdout. Use sys.exit() in Python to do this. In that case, checking for failure is simply when result.rc != 0.

(And of course you should use command instead of shell whenever possible.)


View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.