4

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
Cavaz
  • 232
  • 1
  • 6
Coder
  • 83
  • 1
  • 2
  • 5

2 Answers2

6

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.

Cavaz
  • 232
  • 1
  • 6
3

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.)

Michael Hampton
  • 244,070
  • 43
  • 506
  • 972