How to restrict user in case they are passing empty value in mandatory parameter in custom Ansible module

Viewed 36

I have a custom Ansible module which takes protocol as a parameter and it is a mandatory parameter.

module_args = dict(
        protocol=dict(type='str', required=True),
        protocol_metadata=dict(type='dict', default={})
    )

In the below task, if I don't pass any value in protocol my task is accepting it and setting the value as None in module. But I want my task not to accept None if I am not passing any value in protocol parameter. How to restrict the protocol param to not accept None?

tasks:
  - name: log api request
    my_module:
      protocol:
      protocol_metadata: 
        url: "{{ server }}{{ endpoint }}"
1 Answers

You can make your own validation in Python for those kind of cases, for example:

module_args = dict(
  protocol=dict(type='str', required=True),
  protocol_metadata=dict(type='dict', default={})
)

module = AnsibleModule(argument_spec=module_args)

params = module.params
protocol = params['protocol']

if not protocol:
  module.fail_json("Please provide a non empty protocol")

Which would yield a

TASK [Log api request] ************************************************
fatal: [localhost]: FAILED! => changed=false 
  msg: Please provide a non empty protocol
Related