0

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       ║
╚═══════════╩═════════════════╝
030
  • 5,901
  • 13
  • 68
  • 110
  • @techraf Question has been updated. It is an example of putting the packages in the tasks instead of defining it as a variable – 030 Aug 21 '16 at 12:56
  • I think you are mixing two things. You can define a variable in a task using `set_fact`. Now, to an already too-broad-question "where should the variables be defined?" you added "should I use variables at all?" Ansible is a collaborative, open, elastic project; the fact that 16 places for defining variables evolved over time is because of the needs of different users and different approaches. There's no "one and only way", depending on the problem you want to solve you use different tools. – techraf Aug 21 '16 at 13:05

1 Answers1

0

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.

Henrik Pingel
  • 9,380
  • 2
  • 28
  • 39