How do you run a task only if a variable has been defined, and what happens when it hasn't?
Use the test when: my_service is defined; if the variable doesn't exist, the task is skipped without an error. is not defined is the inverse.
- name: Test Variable is Defined Demo
hosts: all
vars:
my_service: httpd
tasks:
- name: "{{ my_service }} package is installed"
ansible.builtin.dnf:
name: "{{ my_service }}"
when: my_service is defined
Normally, using an undefined variable makes the task fail with an "undefined variable" error. is defined is a Jinja2 test (written with is, unlike a filter written with |) that checks for existence before anything uses the value. Ansible evaluates when before it templates the module arguments, so when the condition is false the task is skipped and the undefined "{{ my_service }}" in its arguments never causes an error.
This makes a variable optional: define it for the hosts that need the package, leave it out for the rest. The opposite test, min_memory is not defined, is useful for printing a clear message or setting a default.
Go deeper:
Tests (official docs) โ the
issyntax and the built-in tests such asdefined.