4. Ansible Role argument specification
Ansible provides the capability to specify a Role’s argument definitions. This feature is limited to inputs, but it can serve as a starting point for defining output properties as well. To demonstrate this capability, we use a simple DuckDuckGo API integration that returns a description of a given person’s name. This use case runs on the controller, so it does not require any managed hosts. It also serves as a recap of roles and collections, with the focus on argument definitions.
The playbook is presented in three versions:
-
duck1.yml - regular playbook interacting with DuckDuckGo API
-
duck2_with_role.yml - playbook with role hiding DuckDuckGo API complexity
-
duck3_with_collection.yml - playbook with collection
Argument validation is defined in the argument_specs.yml
file stored in the meta/
directory.
argument_specs:
main:
short_description: "Query DuckDuckGo"
options:
duckduckgo_query:
type: str
description: The search query to send to DuckDuckGo Instant Answer API
required: true
It is verified at runtime by a task at the start of the Role’s logic, using the validate_argument_spec
module.
- name: Validate inputs (explicit)
ansible.builtin.validate_argument_spec:
argument_spec: "{{ lookup('file', role_path ~ '/meta/argument_specs.yml') | from_yaml }}"
By applying these two simple elements, you ensure that your role receives all required arguments in the expected format.