The Ansible policy for defining variables and constants in the vars, defaults or tasks directory

ansibleansible-playbook

I have read multiple documents including this one and checked multiple ansible roles on GitHub, but it is unclear to me when to define a variable and when one is defined where to put it, i.e. in the defaults, tasks or vars directory.

I would like to receive guidelines so that I do not have to spend a lot of time about thinking whether a variable is required and if that is the case where to put it.

defaults

sensu_host: localhost
sensu_home: /etc/sensu
sensu_conf_d: "{{ sensu_home }}/conf.d"

tasks

- name: be sure {{ item }} is installed
  apt:
    name: "{{ item }}"
    state: latest
  with_items:
    - build-essential
    - ntp

or should the items be defined in a variable:

- name: be sure {{ item }} is installed
  apt:
    name: "{{ item }}"
    state: latest
  with_items:
    {{ packages }}

vars

__sensu_repo_url: deb http://sensu.global.ssl.fastly.net/apt sensu main
__sensu_repo_key_url: http://sensu.global.ssl.fastly.net/apt/pubkey.gp

Is there a certain checklist, e.g.

If a, b, c then the variable needs to be declared in defaults

if d, e, f then the v

if g, h, i then define it in tasks

╔═══════════╦═════════════════╗
║ directory ║ characteristics ║
╠═══════════╬═════════════════╣
║ defaults  ║ constants, e.g. ║
║ tasks     ║ bla, e.g.       ║
║ vars      ║ variables       ║
╚═══════════╩═════════════════╝

Best Answer

There are no policies for defining variables and constants in the vars and defaults directory.

Variables in the role/defaults directory have the lowest priority. So it makes sense to put all the variables defined in the role in role/defaults/main.yml for reference. If a variable default value depends on the distribution I put it under vars/{{ ansible_os_family }}.yml and include it like this:

# Variable setup.
- name: Include OS-specific variables.
  include_vars: "{{ ansible_os_family }}.yml"

I also put variables which are kind of constant like urls under vars as well.

But again there are no real policies. It is up to you how to do things. I personally orientate my role structure and playbook style by geerlingguy.