Generate temaplate file when having with_items and array

I need to generate few files based on jinja template ,

In the first run it is easy when I need to generate single file per user

Basic input:

user:

  • { username: user1, action: get , file: 1.txt }
  • { username: user2, action: get , file: 2.txt }

Jinja template:

User: {{ item.users }}
Permission: {{ item.action}}
File-access: {{ite.file}}

Playbook:

  • name: generate files
    template:
    src: template.j2
    dest: “{{ folder }}/{{ item.username }}”
    with_items: “{{ user }}”

But now comes the twist, Single user can have multi files (see user1) and , I need to create for this user 2 files

File 1 – filename user1-1 , where file = to 1.txt

File 2 – filename user1-2 , where file = to new.file

Advance input:

user:

  • { username: user1, action: get , file: [1.txt ,new.file] }
  • { username: user2, action: get , file: 2.txt }

Any ideas ?

A loop with subelements should give you the control you need to template out what you need based on the number of files in the data structure:

  • name: test jinja rendering
    hosts: localhost
    gather_facts: no

vars:
users:

  • username: user1
    action: GET
    files:
  • file1
  • username: user2
    action: GET
    files:
  • file1
  • file2

tasks:

  • name: debug the data structure
    ansible.builtin.debug:
    msg:
  • Item 0 is ‘{{ item.0 }}’
  • Item 1 is ‘{{ item.1 }}’
    loop: ‘{{ users | subelements(“files”) }}’

Sample debug output:

TASK [debug the data structure] ************************************************
ok: [localhost] => (item=[{‘username’: ‘user1’, ‘action’: ‘GET’, ‘files’: [‘file1’]}, ‘file1’]) => {
“msg”: [
“Item 0 is ‘{‘username’: ‘user1’, ‘action’: ‘GET’, ‘files’: [‘file1’]}’”,
“Item 1 is ‘file1’”
]
}
ok: [localhost] => (item=[{‘username’: ‘user2’, ‘action’: ‘GET’, ‘files’: [‘file1’, ‘file2’]}, ‘file1’]) => {
“msg”: [
“Item 0 is ‘{‘username’: ‘user2’, ‘action’: ‘GET’, ‘files’: [‘file1’, ‘file2’]}’”,
“Item 1 is ‘file1’”
]
}
ok: [localhost] => (item=[{‘username’: ‘user2’, ‘action’: ‘GET’, ‘files’: [‘file1’, ‘file2’]}, ‘file2’]) => {
“msg”: [
“Item 0 is ‘{‘username’: ‘user2’, ‘action’: ‘GET’, ‘files’: [‘file1’, ‘file2’]}’”,
“Item 1 is ‘file2’”
]
}