2

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!

1 Answer 1

2

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"
        }
    ]
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.