Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

templates - Ansible jinja2 templating

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 Reply

0 votes
by (71.8m points)

For example, the playbook

shell> cat pb.yml
- hosts: localhost
  vars:
    containers:
      - {name: a, version: 1}
      - {name: b, version: 2}
  tasks:
    - template:
        src: containers.txt.j2
        dest: containers.txt

and the template

shell> cat containers.txt.j2
{% for item in containers %}
name: {{ item.name }} version {{ item.version }}
{% endfor %}

give

shell> cat containers.txt
name: a version 1
name: b version 2

It's possible to iterate the list

    - debug:
        msg: "image: registry.example.com/container-{{ item.name }}:container_{{ item.version }}_version"
      loop: "{{ containers }}"

gives

  msg: 'image: registry.example.com/container-a:container_1_version'
  msg: 'image: registry.example.com/container-b:container_2_version'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...