Variable definition best practice

108 views
Skip to first unread message

Mpampis Mpigkonias

unread,
Jun 15, 2016, 8:28:36 PM6/15/16
to Ansible Project
Hello,

I use some fact variables in my playbook in my tasks code (I've been using roles). I know that they don't need to be defined in the vars part, but is it a good practice to do so?

I have something like:

hostname: "{{ ansible_hostname }}"
year: "{{ ansible_date_time.year }}"
month: "{{ ansible_date_time.month }}"
day: "{{ ansible_date_time.day }}"
date: "{{ ansible_date_time.date }}"
dest_file: "/tlp_adm/recoverydata/linux/{{ year }}/{{ month }}/{{ day }}/{{ hostname }}.recoverydata.{{ date }}"

 in vars.

while the tasks code does something like this:

- name: Ensure destination path exists
  file: path=/tlp_adm/recoverydata/linux/{{ year }}/{{ month }}/{{ day }} state=directory
- name: Output recovery log
  local_action: template src=tlp_recoveryData.j2 dest="{{ dest_file }}"

I think that defining variables like this on top makes the code a little bit more readable, but I don't know if it makes sense to put everything in variables, like for example the source path or the facts (?).

What is your opinion? What are the best practices on this?


Jason Bornhoft

unread,
Jun 17, 2016, 12:18:05 PM6/17/16
to Ansible Project
I've never set vars inside the playbook but I've seen it done. I'm not really a fan of that structure because different applications/environments might use the same role and having the vars set within the playbooks can cause a lot of problems or unintended consequences.

Without know your entire infrastructure it's difficult to answer but I specify variables in three separate locations
  1. <rolename>/defaults/main.yml
  2. <appname>/group_vars
  3. <appname>/host_vars
Ansible is quite flexible with its handling of variables and allows them to be specified in many different locations. 

Mpampis Mpigkonias

unread,
Jun 23, 2016, 11:18:45 AM6/23/16
to Ansible Project
Thanks for the reply Jason. Maybe I should explain it better.

The part


hostname: "{{ ansible_hostname }}"
year: "{{ ansible_date_time.year }}"
month: "{{ ansible_date_time.month }}"
day: "{{ ansible_date_time.day }}"
date: "{{ ansible_date_time.date }}"
dest_file: "/tlp_adm/recoverydata/linux/{{ year }}/{{ month }}/{{ day }}/{{ hostname }}.recoverydata.{{ date }}"

is already in my <rolename>/vars/main.yml

while the part



- name: Ensure destination path exists
  file: path=/tlp_adm/recoverydata/linux/{{ year }}/{{ month }}/{{ day }} state=directory
- name: Output recovery log
  local_action: template src=tlp_recoveryData.j2 dest="{{ dest_file }}"

is already in <rolename>/tasks/main.yml

My question is, if it is a good practice for these variables to be defined in general, because in my case you can clearly omit them and use them directly (as facts) in the tasks code.
 
Reply all
Reply to author
Forward
0 new messages