Ansible custom module inside of a role

Viewed 1516

I am trying to understand if there is a standard for sharing custom modules. Roles appear to be the way to share code and it sounds like I can include a custom module inside of a role. However, it seems like this complicates how someone would end up using the module since they need to interface through a role:

i.e. Calling a module:

---
- hosts: all
  tasks:
    - my_module:
        say_something: 'Hi'

i.e. Calling a module inside a role:

---
- hosts: all
  tasks:
  - include_role:
       name: my_role
    vars:
      say_something: 'Hi'

If we do include a module in a role, it seems like we have to write the role as an interface, which is more involved and even duplicates code to accept the variables.

So am I correct on this, or is there something I am missing? And if I am correct, is there any article or best practice on this?

2 Answers

Create library directory where your playbook reside and place your custom module .py file inside the library directory, then you can use it inside your playbook.

Here is the directory structure:

playbook.yml
[library]
  |_ your_custom_moudle_1.py
  |_ your_custom_moudle_2.py

So from your Example

- hosts: all
  tasks:
  - include_role:
       name: my_role
    vars:
      say_something: 'Hi'


Now in your role, you can use above var as
- hosts: all
  tasks:
    - my_module:
        say_something: "{{ say_something }}"

You can have different names for variable as well

- hosts: all tasks: - include_role: name: my_role vars: say_something_1: 'Hi'

- hosts: all tasks: - my_module: say_something: "{{ say_something_1 }}"

Now for sharing things, You can look into collections https://docs.ansible.com/ansible/latest/user_guide/collections_using.html

Related