Created
August 27, 2018 21:21
-
-
Save magne/81abe8c801a79e2e1189e7dd619bccca to your computer and use it in GitHub Desktop.
Jinja2: nested for loop where inner loop is determined by outer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
haproxy_listener: | |
- name: api | |
port: 6443 | |
group: kube-master | |
- name: http | |
port: 80 | |
group: kube-master | |
- name: https | |
port: 443 | |
group: kube-master | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
localhost ansible_hostname=127.0.0.1 ansible_connection=local | |
[load-balancer] | |
kube-00 ansible_hostname=10.0.0.10 | |
[kube-master] | |
kube-01 ansible_hostname=10.0.0.11 | |
kube-02 ansible_hostname=10.0.0.12 | |
kube-03 ansible_hostname=10.0.0.13 | |
[kube-node] | |
kube-04 ansible_hostname=10.0.0.14 | |
kube-05 ansible_hostname=10.0.0.15 | |
kube-06 ansible_hostname=10.0.0.16 | |
[k8s-cluster:children] | |
kube-master | |
kube-node |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
- hosts: load-balancer | |
gather_facts: false | |
tasks: | |
- name: expand | |
set_fact: | |
val: | | |
{% set ns = namespace(v=[],srv=[]) %} | |
{% for i in range(haproxy_listener|length)|list %} | |
{% set entry = haproxy_listener[i] %} | |
{% set ns.srv = [] %} | |
{% set group = entry.pop('group', None) %} | |
{% for host in groups[group] %} | |
{% set ns.srv = ns.srv + [ { 'host': hostvars[host].ansible_hostname, 'port': entry.port}] %} | |
{% endfor %} | |
{% set ns.v = ns.v + [ haproxy_listener[i] | combine({ 'i': i, 'servers': ns.srv }) ] %} | |
{% endfor %} | |
{{ ns.v }} | |
- name: test | |
debug: | |
msg: "{{ (val | to_nice_json).split('\n') }}" | |
delegate_to: localhost | |
run_once: true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
haproxy_listener[i].group
key will be replaced with ahaproxy_listener[i].servers
array of dictionaries populated based on thegroups[group]
inventory host group.