Pass 'ansible_failed_result' variable to Tower Notification

I’m trying to find a way to use the native Ansible and Tower failure variables and notifications respectively to send an email with the result of a job’s execution output.

So I have a playbook that does something like this:

rescue:

- debug:
msg: “Failure:\n\n{{ansible_failed_result | to_nice_json}}”

Which gives me a nice output in Tower

However I’d also like to be able to pass that same output from Tower to an email notification so that I can see in an email the output of a job without having to log into Tower. This means I know from my email right away if it’s a connection timeout or something more serious.

I’ve tried using the customize notifications in Tower and have tried the ‘job.job_explanation’ field, however that always returns empty.

I tried running the job with increased verbosity, but that didn’t work either.

Any ideas of how to do this?
At this point I’m not sure I’m even on the right track using the job_explanation field so any help would be much appreciated!

Thanks,
Dave

Job_explanation isn’t going to be fruitful. Unfortunately we do not save the “magic” ansible_failed_result. But it would be cool if we did.

Make a workflow. Have the first job call set_fact with cacheable set to yes and fact caching turned on in tower. Link the second job as failure only. Attach a notification to the second job and use artifacts in the jinja template
https://github.com/ansible/awx/blob/2c7d9320e295520cd4549cbcdc6f441b477593ce/awx/main/models/notifications.py#L287

You might not even need two nodes. I can’t remember if workflows support notifications.

Would this be the only way to have custom messages defined in the Playbook bubbled back up to the Tower notification level?

I’m not sure the workflow idea will work for my purposes as I want to implement this in all of my templates - having a bunch of workflows just to send out notifications seems a bit messy

Thanks for the help

I think you can do this at a job template level but can’t be sure. You should see artifacts on the job if it has a chance at working.

Thanks Chris,

I got it working mostly how I’d like which is a great improvement so far! Few more questions but that’s for another post

In case anyone else stumbles across the same issue, here’s how I did it very simply

tasks:

  • block:
  • name: Fail Task
    fail:
    msg: ‘Failed’
    when: true

rescue:

  • name: set stats
    set_stats:
    data:
    msg_body_1: “This was a test”

You can then use {{ job.artifacts }} in the Tower notifications message section to return the variable you set.