How to figure out in callback plugin if Ansible runs in check-mode?

In other plugin types there is something like self._play_context.check_mode available. I can’t figure out how to check this in a callback plugin though. All callback plugins which ship with Ansible 2 do not prevent any execution when check-mode is on.

This is quite important for notification type callbacks. You probably do not want to send emails, hipchat messages etc when the playbook is executed with –check

When inspecting the play parameter of the callback v2_playbook_on_play_start it appears it has a check_mode attribute:

def v2_playbook_on_play_start(self, play): pprint(dir(play))

But any attempt to use it end in

[WARNING]: Error when using <bound method CallbackModule.v2_playbook_on_play_start of <my.CallbackModule object at 0x2a0e050>>: ‘check_mode’

Also looking at the class there is no such method or property defined. No idea why dir() would show that.

lib/ansible/playbook/play_context.py seems the only class which provides this info but it seems to be not available anywhere in the callback module.

Can anyone help with this?

Thanks,
Daniel

In your callback file add the following to your imports:

try:
from main import cli
except ImportError:
cli = False

Then in init for your CallbackModule add something like:

if cli and cli.options.check:
self.disabled = True

Awesome, that indeed works. Thank you Matt!

To add to this, if you are ever planning to use python to call a playbook (with PlaybookCLI) that uses a callback that does this, you will need to add cli and mycli to your main.

e.g. make this a global variable:

cli = PlaybookCLI(['ansible-playbook', '-i', 'hosts', 'site.yml', '--check'])

That way, cli will still show up main so you won’t get an import error.