how to count success and failure of a task ?

Hi Guys,

I am verifying Cisco IOS image via this playbook, this runs great. However, I would like to add a count on successful and failure of the task I run. How can I achieve that?

For eg. I have 100 devices to verify code out of which 95 made a successful upgrade and 5 does not make, from the below playbook how can I add a count ? to capture no. of successful upgrade and failure?

Please help ?

If you have the results registered in 'myvar' (assuming loop) you
should be able to get a count like:

debug: msg="{{(myvar.results|select('failed'))|length}}"

Hi Brian,

I tried your solution, my playbooks run successfully but not giving desired output.

I used it like below in my playbook:-

  • name: Standard OS Validation after Upgrade.
    set_fact:
    standard_OS: “{{ item.1 }}”
    when:

  • item.1 == “15.0(2)SG10,”
    with_indexed_items: “{{ sh_ver.stdout[0].split() }}”

  • fail:
    msg:

  • “Standard OS is not on this device {{ lookup(‘dig’, hostip, ‘qtype=PTR’) }}”
    when:

  • ‘standard_OS is undefined’
    register: myvar.results

  • debug: msg=“{{(myvar.results|select(‘failed’))|length}}”

That’s output I get:-

TASK [fail] ********************************************************************
task path: /home/user/ansible/po-ios-va.yml:36
skipping: [switch_A] => {“changed”: false, “skip_reason”: “Conditional check failed”, “skipped”: true}
fatal: [switch_B]: FAILED! => {“changed”: false, “failed”: true, “msg”: [“Standard OS is not on this device switch_B.”]}

TASK [debug] *******************************************************************
task path: /home/user/ansible/po-ios-va.yml:42
fatal: [switch_A]: FAILED! => {“failed”: true, “msg”: “Unexpected templating type error occurred on ({{ (myvar.results|select("failed"))| length }}): object of type ‘generator’ has no len()”}
to retry, use: --limit @/home/user/ansible/po-ios-va.retry

Please Suggest.

register: myvar.results <= this is incorrect, you cannot register to
a subindex.

correct:
register: myvar

you get myvar.results IF that task has with_.

I really don't understand what you are trying to do or why the first
task would even continue if there are any failed items as that would
fail the whole task.

sure thing, guess I need work on my code more, it is still workable as expected.

Appreciate your help Brian.