I have an Ansible Custom Module for performing a specific task in my playbook. I want to debug specific variables inside this module.
Is there a way we can print anything inside this custom module? In the example below, print "Hello".
Please check the following snippet from the Custom Module. I am passing a jobid
as an argument to this module.
class dcsjob():
def __init__(self, arglist):
self.jobid = self.arglist[0]
def checkandwaitforjob(self):
print("Hello")
def run_module():
module = AnsibleModule(
argument_spec=module_args,
supports_check_mode=True
)
dcsjobobj = dcsjob([module.params['jobid']])
output = dcsjobobj.checkandwaitforjob()
Given an example module from Developing modules- Creating a module with modification
library/print.py
#!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.module_utils.basic import AnsibleModule
def run_module():
module_args = dict(
jobid=dict(type='str', required=True),
verbose=dict(type='bool', required=False, default=False)
)
result = dict(
changed=False,
jobid=''
)
module = AnsibleModule(
argument_spec=module_args,
supports_check_mode=False
)
result['jobid'] = module.params['jobid']
if module.params['verbose']:
result['print'] = 'Hello'
module.exit_json(**result)
def main():
run_module()
if __name__ == '__main__':
main()
and called from an example playbook print.yml
---
- hosts: localhost
become: false
gather_facts: false
vars:
ID: 123
tasks:
- name: Run non-verbose
print:
jobid: "{{ ID }}"
verbose: false
register: result
- name: Show result
debug:
msg: "{{ result }}"
- name: Run verbose
print:
jobid: "{{ ID }}"
verbose: true
register: result
- name: Show verbose result
debug:
msg: "{{ result }}"
it will result into an output of
TASK [Run non-verbose] **********
ok: [localhost]
TASK [Show result] **************
ok: [localhost] =>
msg:
changed: false
failed: false
jobid: '123'
TASK [Run verbose] **************
ok: [localhost]
TASK [Show verbose result] ******
ok: [localhost] =>
msg:
changed: false
failed: false
jobid: '123'
print: Hello
printing the jobid
, and Hello
only when in verbose
mode.
This could also be utilized with check_mode
module_args = dict(
jobid=dict(type='str', required=True)
)
result = dict(
changed=False,
check_mode=False,
jobid=''
)
module = AnsibleModule(
argument_spec=module_args,
supports_check_mode=True
)
result['jobid'] = module.params['jobid']
if module.check_mode:
result['check_mode'] = True
result['print'] = 'Hello'
which would change the behavior if --check
is applied or not.
Further Documentation
Debugging modules - Simple debugging
Since
print()
statements do not work inside modules, raising an exception is a good approach if you just want to see some specific data.