How to Make Ansible variable mandatory

Viewed 18134

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)
5 Answers

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.

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
Related