Introduction

Ansible does not provide a standard way to check that required variables are defined before executing a tsak.
Ansible, relies instead on the standard mechanism of a task failing if a variable being used has not been defined.

Sometimes you want to make sure that all required variables are defined before starting the tasks for a role.

Define the required variable for a role

In your role default, define a list named requred_vars where you can declare required variables:

/roles/defaults/main.yml :

required_vars:
  - var1
  - var2
  - var3

Check that all variables are defined

As a first task for your role, check that all required variables have been defined. If a variable in the liste has not been defined, this first task will fail.

 

/roles/tasks/main.yml :

name: "Check required variables"
  fail: msg="Variable '{{ item }}' is not defined"
  when: item not in vars
  with_items: "{{required_vars}}"

 

Advertisements