How to Make Ansible variable mandatory

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

Usually inside a role I perform checking input variables like in the example:

- name: "Verify that required string variables are defined"
  assert:
    that: 
      - "{{ ahs_var }} is defined"
      - "{{ ahs_var }} | length > 0"
      - "{{ ahs_var }} != None"
    fail_msg: "{{ ahs_var }} needs to be set for the role to work"
    success_msg: "Required variable {{ ahs_var }} is defined"
  loop_control:
    loop_var: ahs_var
  with_items:
    - ahs_item1
    - ahs_item2
    - ahs_item3

by the way there are some tricks:

  1. Don't use global variables inside a role.
  2. If you want use global variables define the role specific variable & set global variable to it i.e. some_role_name__db_port: "{{ db_port | default(5432) }}".
  3. It makes sense to use role name as the prefix for variable. it helps to understand the source inventory easier.
  4. Your role might be looped some how, so it makes sense to override the default item.

You can use this:

{{ variable | mandatory }}

One way to check if mandatory variables are defined is:

- fail:
    msg: "Variable '{{ item }}' is not defined"
  when: item not in vars
  with_items:
    - app_nam
    - var2

Tags:

Ansible