HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Looping through hosts from an inventory group in a group_vars file

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
loopingfilehostsgroupinventorygroup_varsthroughfrom

Problem

Is it possible to do something like this:

# inventories/inventory1/group_vars/group1

filewatches:
    {% for host in groups['group2'] %}
    - type: "copy"
      directory_name: "{{ host }}"
      shell_script: "{{ script_dir }}/ascript.sh"
     {endfor %}
    - type: "anotherone"
      ...


# inventories/inventory1/hosts

[group1]
somemachine01

[group2]
machine1
machine2
machine3
...


Basically, I want to generate a bunch configuration that is similar except for just one variable (in this case the directory_name variable). I would rather do this than making 20+ different entries which all differ by JUST the directory_name variable.

I did not include the playbook or roles information for the sake of clarity/terseness. I hope I was clear enough and gave enough context, and I appreciate any help.

Thanks!

Solution

Yes. It is possible to create a YAML data structure with Jinja and read the variable in with the filter from_yaml.

The play

- hosts: group1
  vars:
    script_dir: /tmp
  tasks:
    - debug:
        var: filewatches


with the group_vars

$ cat group_vars/group1.yml 
filewatches: "{{ filewatches_var|from_yaml }}"
filewatches_var: |
    {% for host in groups['worker'] %}
    - type: "copy"
      directory_name: "{{ host }}"
      shell_script: "{{ script_dir }}/ascript.sh"
    {% endfor %}


and with the inventory

$ cat hosts
...
group1:
  hosts:
    test_01

group2:
  hosts:
    test_02
    test_03


gives

ok: [test_01] => {
    "filewatches": [
        {
            "directory_name": "test_02", 
            "shell_script": "/tmp/ascript.sh", 
            "type": "copy"
        }, 
        {
            "directory_name": "test_03", 
            "shell_script": "/tmp/ascript.sh", 
            "type": "copy"
        }
    ]
}

Code Snippets

- hosts: group1
  vars:
    script_dir: /tmp
  tasks:
    - debug:
        var: filewatches
$ cat group_vars/group1.yml 
filewatches: "{{ filewatches_var|from_yaml }}"
filewatches_var: |
    {% for host in groups['worker'] %}
    - type: "copy"
      directory_name: "{{ host }}"
      shell_script: "{{ script_dir }}/ascript.sh"
    {% endfor %}
$ cat hosts
...
group1:
  hosts:
    test_01

group2:
  hosts:
    test_02
    test_03
ok: [test_01] => {
    "filewatches": [
        {
            "directory_name": "test_02", 
            "shell_script": "/tmp/ascript.sh", 
            "type": "copy"
        }, 
        {
            "directory_name": "test_03", 
            "shell_script": "/tmp/ascript.sh", 
            "type": "copy"
        }
    ]
}

Context

StackExchange DevOps Q#9168, answer score: 2

Revisions (0)

No revisions yet.