Ansible loop over variable integer and incremente value for jinja template

Viewed 323

I have a ansible playbook, I wanto to loop over a interger and incremente a value for each file create, like that :

file_a :

name = a
number = 20

file_b

name = b
number = 21

playbook.yml

- name: Copy file from jinja template
  template:
    src: "jinja.j2"
    dest: "/file_{{ item }}"
    owner: "root"
    group: "root"
  with_items: "{{ jinja_var }}"

inventory.yml

jinja_var:
  - a
  - b

jinja.j2

name = {{ item }}
number  =

I have a solution with a dict who works with key, value, but I don't want to modify the inventory.yml, so hwo I can give a incremente integer through a jinja file

1 Answers

Use loop_control. For example the template

shell> cat templates/jinja.j2 
name = {{ item }}
number = {{ index + offset }}

and the playbook

shell> cat playbook.yml
- hosts: localhost
  vars:
    jinja_var: [a, b]
    offset: 20
  tasks:
    - template:
        src: jinja.j2
        dest: "files/file_{{ item }}"
      loop: "{{ jinja_var }}"
      loop_control:
        index_var: index

give

shell> cat files/file_a 
name = a
number = 20

shell> cat files/file_b
name = b
number = 21
Related