How do you make roles fail fast on bad input?
IntermediateProductionTesting, CI/CD and Quality
Answer
Validate inputs before the role changes anything, so a typo fails in the first second instead of leaving a host half configured.
meta/argument_specs.ymldeclares types, required options and choices; Ansible checks them automatically when the role starts.ansible.builtin.assertcovers rules a schema cannot express, such as cross-field checks.
- name: Validate inputs
ansible.builtin.assert:
that:
- app_port | int > 1024
- app_env in ['dev', 'staging', 'prod']
- not (app_env == 'prod' and app_debug | bool)
fail_msg: "Invalid inputs for app role: check app_port, app_env and app_debug"
quiet: true
Put the validation at the top of tasks/main.yml and give clear fail_msg text. The person who sees it at 2 AM did not write the role.
More on Testing, CI/CD and Quality
What does a testing pyramid look like for Ansible code?BeginnerHow do you roll out `ansible-lint` profiles across a team without blocking everyone?IntermediateWhen do you use `skip_list`, `warn_list` and `# noqa`?IntermediateHow do you set up pre-commit hooks for an Ansible repo?BeginnerHow is a Molecule scenario laid out, and what does `molecule test` actually run?IntermediateDocker, Podman or real VMs as the Molecule driver: how do you choose?Advanced