delegate_to and when

I have a playbook that executes a command on a set of routers (inventory hosts) looking for a specific IP address. The playbook uses the “meta: end_host” on hosts that do not return a desired result. This works fine. A result is returned to the user via a URI call.
Now I’d like to return “not found” with the URI call, when none of the routers have the IP address. Unfortunately the meta:end_host ends the playbook.
I’ve tried setting a “flag” on localhost as ansible_fact but the when does not work.

  • name: Set default value for ip not_found flag
    set_fact:
    not_found: true
    delegate_to: localhost
    delegate_facts: true
    run_once: yes

  • name: Set default value for ip not_found flag
    set_fact:
    not_found: true
    delegate_to: localhost
    delegate_facts: true
    run_once: yes

  • name: NOT FOUND
    uri:
    url: https://{{ cmdb }}/{{ test_results }}
    method: PUT
    body_format: json
    body: {
    “jobId”: “{{ tower_job_id | default(‘000’)}}”,
    “result”: “Search for IP Address {{ realtime_ip }}”,
    “details”: “NOT FOUND”
    }
    delegate_to: localhost
    when: not_found

The last play does not delegate to localhost so I get an error that not_found does not exist. What I’m I doing wrong. Any other way I can accomplish this. I dont want “failed” hosts from the playbook.

TASK [NOT FOUND] *******************************************************************************************************************************************************************************
task path: /home/smitsi1/tower-network-playbooks/find_ip_mac_realtime.yml:155
fatal: [router-lab-srp.gw.mcgill.ca]: FAILED! => {
“msg”: “The conditional check ‘not_found’ failed. The error was: error while evaluating conditional (not_found): ‘dict object’ has no attribute ‘not_found’\n\nThe error appears to be in ‘/home/smitsi1/tower-network-playbooks/find_ip_mac_realtime.yml’: line 155, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n # Check if None of the routers have an ARP then IP not found. Want to return "not found" to NetMan\n - name: NOT FOUND DEBUG\n ^ here\n”
}

when statements, as well as other templating in a task, uses the context of the target host in the play, not the delegated host.

You could use hostvars.localhost.not_found instead in the when statement.