Pages

Monday, August 8, 2016

Ansible Custom Module – Using Python

In the previous article we have seen how we can write out custom module using shell script. In this article we can see how to write a custom module using Python

1. Write out Python Code – lets write a Python script named as “echo” which will take an argument and print the string passed

[root@puppet centos7]# cat ./library/echo
def main():
    module = AnsibleModule(
             argument_spec = dict(
                name=dict(required=True),
                success=dict(default=True,type='bool'),),
    )

    Success= module.params['success']
    text=module.params['name']

    if success:
        module.exit_json(msg=text)
    else:
        module.exit_json(msg=text)


from ansible.module_utils.basic import *
main()

In the above snippet,

1. main() is the entry point for the module
2. AnsibleModule comes from from ansible.module_utils.basic import *. It has to be imported with the *
3. AnsibleModule helps us handle incoming parameters and exiting the program (module.exit_json()).
4. AnsibleModule provides features to handle the module arguments. It allows us to specify if the arguments are required or optional. It also handles some data types such as ‘Boolean’.
5. Existing the module is done by using "module.exit_json" for successfull return and "module.fail_json" for a failed task

In the above module we taking an 2 arguments success and text which are send as an argument from the playbook. The text value is displayed based on the True|false value that we pass to success argument.


2. Test the Module using our playbook written as,
[root@puppet centos7]# cat sample.yml
---
- hosts: all
  tasks:

   - name: Test My Ansbile Python Module
     echo: name="Testing a Python Module"
     register: user

   - debug: msg="{{ user.msg }}"


3. Executing the playbooks gives us,
[root@puppet centos7]# ansible-playbook sample.yml

PLAY [all] *********************************************************************

TASK [setup] *******************************************************************
ok: [172.16.202.96]

TASK [Test My Ansbile Python Module] *******************************************
ok: [172.16.202.96]

TASK [debug] *******************************************************************
ok: [172.16.202.96] => {
    "msg": "Testing a Python Module"
}

PLAY RECAP *********************************************************************
172.16.202.96              : ok=3    changed=0    unreachable=0    failed=0  

We can see a from the above output that the value passed is given as a output in our Ansible playbook.


This is how we can use Python in writing our custom modules. More to Come. Happy learning J

1 comment :

  1. Thank you for submitting such wonderful content and very informative and useful for Ansible learners. We are very happy to recieve such wonderful content and highly informative and one of the recommanded sites for Ansible learners

    ReplyDelete