How to repeat a set of tasks for each var file and flush the previous hashed vars?

Hi everyone,

I currently try to build up a config repository for multiple departments. Every department has it’s own var file with a fixed format. This helps us to better analyze incoming changes in a merge request.

for example:
vars/qualitygates/department1.yml

qualitygate:
  - qualitygate_name: codeverify
    operators: 
      - metric: cover
        operator: test1
        error: 1
  - qualitygate_name: department_analysis
    operators: 
      - metric: cover_unverified
        operator: test2
        error: 2
     - metric: quality
       operator: LT
       error: 0

the file for my next department:

vars/qualitygates/department2.yml

qualitygate:
  - qualitygate_name: codequality
    operators: 
      - metric: cover
        operator: test3
        error: 1
      - metric: security
        operator: GT
        error: 3
  - qualitygate_name: conditions
    operators: 
      - metric: cover_unverified
        operator: test4
        error: 2

Unfortunately including multiple var files with identical key’s will be overwritten with the newest. More information about that here. Ansible Configuration Settings — Ansible Community Documentation

I could set DEFAULT_HASH_BEHAVIOUR to merge, but that is not recommended and I should use combine, vars and varnames…
However these modules require non-identical key’s

Regarding my thread title, I try to achieve the configuration as code for a service.
I am unsure here what might be the better solution…
Never done this before…
Should I…
…change the dict’s to have a unique key and adjust my tasks?
…use a loop that includes a var file, run tasks, drop vars and include the next file?

I think you could do something like this. The key being that include_vars allows you to store the included variables inside another variable so theres no conflict

- hosts: localhost
  vars:
    departments:
      - a
      - b
  tasks:
    - name: Include different department vars
      ansible.builtin.include_vars:
        file: department_{{ item }}_vars.yml
        name: dep_{{ item }}_vars
      loop: "{{ departments }}"
    - name: Print Department Vars
      ansible.builtin.debug:
        var: lookup('ansible.builtin.vars',  'dep_' + item + '_vars')
      loop: "{{ departments }}"

1 Like

I think you should

because variables are meant to be overwritten according to this precedence in Ansible.