hmar
hmar

Reputation: 117

How to iterate through nested items in Ansible

I'm not sure if i'm taking the correct way but i have the next problem.

I need a simple task like:

  - name: Copying files
    template:
      src: "{{ item[1] }}.j2"
      dest: "{{ path }}/{{ item[0] }}/{{ item[1] }}"
    with_nested:
      - [ 'env1' , 'env2' ]
      - [ 'file1' , 'file2']

Actual results:

/path/env1/file1
/path/env1/file2
/path/env2/file1
/path/env2/file2

Expected results:

/path/env1/file1
/path/env2/file2

I just need that file1 generate template in directory env1 and the file2 generate template in env2. I can't do it with a simple 'with_items' because i hace 2 items to iterate, the name of the directory and the name of the file.

I'm sure that there is a way to do that correctly..

Thanks in advance

Upvotes: 0

Views: 176

Answers (2)

Ravi Kulkarni
Ravi Kulkarni

Reputation: 667

you can try following to get expected results :

  - name: Copying files
    template:
      src: "{{ item[1] }}.j2"
      dest: "{{ path }}/{{ item[0] }}/{{ item[1] }}"
    with_together:
      - [ 'env1' , 'env2' ]
      - [ 'file1' , 'file2']

with_together explanation

Upvotes: 0

Vladimir Botka
Vladimir Botka

Reputation: 67984

Use zip filter. The play below

- hosts: localhost
  vars:
    list1: [ 'env1' , 'env2' ]
    list2: [ 'file1' , 'file2']
  tasks:
    - debug:
        msg: "/path/{{ item.0 }}/{{ item.1 }}"
      loop: "{{ list1|zip(list2)|list }}"

gives (grep msg):

    "msg": "/path/env1/file1"
    "msg": "/path/env2/file2"

Upvotes: 0

Related Questions