Jinja2 reuse set vars as filter

I ask you for help to solve my filter problem on Jinja2.

my_vars.yaml

nodes:  
  - name: m01
    port: 7001
    bus_port: 17001
  - name: m02
    port: 7002
    bus_port: 17002
  - name: m03
    port: 7003
    bus_port: 17003
  - name: s01
    port: 7011
    bus_port: 17011
    replicaof: m01
  - name: s02
    port: 7012
    bus_port: 17012
    replicaof: m02
  - name: s03
    port: 7013
    bus_port: 17013
    replicaof: m03

example.conf.j2

{% if nodes.name|first in 's' %}
{% set n = nodes.replicaof %}
{{ n }}
{% endif %}

result: m01

I would like to reuse the 'm01' to retrieve the port and the name and possibly other information when I loop on the service 's01'

When I work on node s01. I would like to find who is master and collect the information from node m01.

Working Node :

- name: s01 
  port: 7011 
  bus_port: 17011 
  replicaof: m01 

expected result:

m01 7001

Thanks for your help.

1 answer

  • answered 2021-02-23 01:49 jtyr

    This Jinaj2 template works:

    {% for n in nodes if n.name.startswith('s') %}
      {%- if loop.first -%}
        {{ n.name }} {{ n.port }}{{ "\n" }}
      {%- endif %}
    {%- endfor %}
    

    Teste with this playbook:

    ---
    
    - hosts: all
      gather_facts: no
      connection: local
      vars:
        nodes:
          - name: m01
            port: 7001
            bus_port: 17001
          - name: m02
            port: 7002
            bus_port: 17002
          - name: m03
            port: 7003
            bus_port: 17003
          - name: s01
            port: 7011
            bus_port: 17011
            replicaof: m01
          - name: s02
            port: 7012
            bus_port: 17012
            replicaof: m02
          - name: s03
            port: 7013
            bus_port: 17013
            replicaof: m03
      tasks:
        - template:
            src: example.conf.j2
            dest: /tmp/example.conf
    

    Executed like this:

    ansible-playbook -i localhost, --diff main.yaml
    

    With this result:

    PLAY [all] *******************************************************************************************************
    
    TASK [template] **************************************************************************************************
    --- before
    +++ after: /home/user/.ansible/tmp/ansible-local-6181175x24f2u2/tmp_7beb37a/example.conf.j2
    @@ -0,0 +1 @@
    +s01 7011
    
    changed: [localhost]
    
    PLAY RECAP *******************************************************************************************************
    localhost                  : ok=1    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0