Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Make Ansible variable mandatory

Tags:

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)
like image 342
Alexey Bakulin Avatar asked Jul 10 '17 13:07

Alexey Bakulin


People also ask

What is variable precedence in Ansible?

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.

How do I register variables in Ansible?

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.

Which filter is used to provide default values to variables Ansible?

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) }} ?


2 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
like image 133
Alexey Vazhnov Avatar answered Oct 11 '22 22:10

Alexey Vazhnov


You can use this:

{{ variable | mandatory }}
like image 21
Arbab Nazar Avatar answered Oct 11 '22 21:10

Arbab Nazar