1up
1up

Reputation: 81

Nested arguments for Ansible Module

I am developing an Ansible module. Is it possible to specify a set of arguments as required when one argument has a certain value?

For example, if my module has a 'state' argument that can be either 'present' or 'absent', is it possible to require an additional set of arguments like 'type', 'path' only when state=present?

module_args = dict(
   name=dict(type='str', required=True),
   type=dict(type='str', required=False),
   path=dict(type='str', required=False),
   state=dict(type='str', required=False, choices=["present","absent"]
}

module = AnsibleModule(
   argument_spec=module_args,
   supports_check_mode=True
)

name = module.params["name"]
script_type = module.param["type"]
path = module.param["path"]
state = module.state["state"]

Upvotes: 1

Views: 1880

Answers (3)

Y.Y.
Y.Y.

Reputation: 121

Not sure if too late, but you can do exactly this with the following.

module_args = dict(
   name=dict(type='str', required=True),
   type=dict(type='str', required=False),
   path=dict(type='str', required=False),
   state=dict(type='str', required=False, choices=["present","absent"]
)

required_if_args = [
   ["state", "present", ["type", "path"]]
]

module = AnsibleModule(
   argument_spec=module_args,
   required_if=required_if_args,
   supports_check_mode=True
)

This states that if state=present, type and path are required.

Upvotes: 1

1up
1up

Reputation: 81

Though there is no such concept as nested parameters in Ansible (AFAIK), there are other concepts that may accomplish the same intent:

  • required_together
  • required_one_of
  • required_if

With the above declarations, one can make associations between parameters -- that is put in logic where if one parameter is specified, another may be asked to be specified with it.

Or if a certain value is specified for a parameter (i.e. State=present), additional parameters may be asked to be specified with that parameter (given its value).

Joe Seeder's blogpost covers this in more detail.

Upvotes: 0

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68269

As far as I know there is no such ability in current Ansible 2.3.

There is only required_together option for AnsibleModule class to define parameters that should be supplied together (but there is no condition on its value):

 required_together = [['s3_key', 's3_bucket'],
                     ['vpc_subnet_ids', 'vpc_security_group_ids']]

So you should do manual checks for that.

Upvotes: 1

Related Questions