I'm looking for the way how to make Ansible to analyze playbooks for required and mandatory variables before run playbook's execution like:
- name: create remote app directory hierarchy
file:
path: "/opt/{{ app_name | required }}/"
state: directory
owner: "{{ app_user | required }}"
group: "{{ app_user_group | required }}"
...
and rise error message if variable is undefined, like:
please set "app_name" variable before run (file XXX/main.yml:99)
In general, Ansible gives precedence to variables that were defined more recently, more actively, and with more explicit scope. Variables in the defaults folder inside a role are easily overridden. Anything in the vars directory of the role overrides previous versions of that variable in the namespace.
Ansible registers are used when you want to capture the output of a task to a variable. You can then use the value of these registers for different scenarios like a conditional statement, logging etc. The variables will contain the value returned by the task. The common return values are documented in Ansible docs.
So if you want to define a default value for a variable you should set it in role/defaults/main. yml . Ansible will use that value only if the variable is not defined somewhere else. Using the Jina2 filters is it possible to do something like {{ variable | default(other_variable) }} ?
As Arbab Nazar mentioned, you can use {{ variable | mandatory }}
(see Forcing variables to be defined) inside Ansible task.
But I think it looks nicer to add this as first task, it checks is app_name
, app_user
and app_user_group
exist:
- name: 'Check mandatory variables are defined'
assert:
that:
- app_name is defined
- app_user is defined
- app_user_group is defined
You can use this:
{{ variable | mandatory }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With