Variable definition best practice

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?

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. /defaults/main.yml

  2. /group_vars

  3. /host_vars

Ansible is quite flexible with its handling of variables and allows them to be specified in many different locations.

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 /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 /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.