Run Ansible task conditionally and fail if condition is not met

ansibleansible-playbook

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

Best Answer

You have three options:

Use failed_when to make the playbook fail checking a condition. I'd suggest to add a exit code to the python script (e.g.: exit(255 if error else 0)), it's cleaner than parsing the stdout:

- name: Check Value
  shell: /usr/bin/python3 check.py
  args:
    chdir: "mydir/scripts/"
  register: result
  failed_when: result.rc != 0
  tags: data_merge

fail will kill the application printing an error message:

- name: Fail on not valid
  fail:
    msg: failed
  when: result.stdout != 'valid'

meta: end_play will silently stop the application (but this may not be useful if you want a feedback output)

- name: Stop on not valid
  meta: end_play
  when: result.stdout != 'valid'

Either way you don't need the when: result.stdout == 'valid' in the Merge Data anymore.