Ansible Modules

Hi guys!

I wrote a small code inside modules and all is good. The only problem that I have, is when I want to print some message on the tasks (informational).

For example:

if I have a for inside my code I want that on each loop print some like

print (still running loop")

I tried a lot of things but still don’t see any message.

This is my code: (PRINT XXX is where I want to print)


import requests
import json
import time
from ansible.module_utils.basic import AnsibleModule

def run_module():
    module_args = dict(
        url=dict(url='str', required=True),
        loop=dict(loop='int', required=False, default=False),
        loopTime=dict(loop='int', required=False, default=False))

    result = dict(changed=False,original_message='',message='')
    module = AnsibleModule(argument_spec=module_args,supports_check_mode=True)

    if module.check_mode:
        return result

    for i in range (1,int(module.params['loop'])):
        try:
            r = requests.get(module.params['url'])
            json_response = json.loads(r.text)

            if json_response['measurements'][0]['value'] == 1:
                 module.fail_json(changed=True, msg="Circuit open!!!")
                 PRINT XXXXXXX
        except Exception as e:
            module.fail_json(msg=e)

        PRINT XXXXX

        time.sleep(float(module.params['loopTime']))
    module.exit_json(changed=False, msg='Circuit is stable')

def main():
    run_module()

if __name__ == '__main__':
    main()


If the process ‘running’ is external, it’s probably best to just use an until loop. That’s what I did with my module.

By until loop, i mean have ansible just re-run the module until it gets success.
like this;

  • name: wait for aerospike migrations
    some_module:
    some_param: foo
    register: mymodule
    until: mymodule is succeeded
    delay: 60
    retries: 120

Hi guys!

I wrote a small code inside modules and all is good. The only problem that I have, is when I want to print some message on the tasks (informational).

[…]

In most cases print() in a module will not work as expected because
the module code is copied to the remote host before it is executed.
So usually the print does not happen on the same host where your
playbook is running.

As already suggested asynchronous execution [1] might be the better
approach here.

[1] https://docs.ansible.com/ansible/latest/user_guide/playbooks_async.html