Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

jinja2 templating - Ansible

In Ansible, I currently have vars set out like this


    container_a_version: 1
    container_b_version: 6
    container_c_version: 3
    container_d_version: 2
    ...


    containers:
     - container_a
     - container_b
     - container_c
     - container_d  
    ... 

Each container has its own template file which has a line like this


    image: registry.sportpesa.com/sportpesa/global/container-a:{{ container_a_version }}

My playbook


    - name: Copy templates
      template:
        src: templates/docker-compose-{{ item }}.yml
        dest: /srv/docker-compose-{{ item }}.yml
      loop: "{{ containers }}"

If I want to deploy only container a and c. I change my variable to this


    containers:
     - container_a
    # - container_b
     - container_c
    # - container_d 

 

What I want to do condense my variables to just have 1 var like this

    containers:
      - { name: a, version: 1 }
      - { name: b, version: 6 }
      - { name: c, version: 3 }
      - { name: d, version: 2 }

However I'm not sure how I can call the container version in my template. Is this possible?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In your loop , you can call a field of the item looped like this :

name: {{ item.name }}
version: {{ item.version }}

I assume you have to put this in your scpecific context. Looks this documentation for more details about jinja templating if necessary.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...