0

I am trying to create somehow a nested loop with comma separated item.values in Ansible. vars: - my_resources - { name: 'share1', id: 'user1,user2,user3' } - { name: 'share2', id: 'user4' }

- name: Create users files
  copy:
  dest: "/etc/vsftpd_users/{{ item.id }}"
  content: |
    local_root=/vol/{{ item.name }}
  with_items: 
  - "{{ my_resources.split(',') }}" 

My expectation should be as below, like every file gets created with appropriate contents inside.

$ cat user1
share1

$ cat user2
share1

$ cat user4
share2

However the files created like below with the above script

-rw-r--r-- 1 root root 22 Oct 11 08:15 [u'user1', u'user2', u'user3']
-rw-r--r-- 1 root root 29 Oct 11 08:15 [u'user4']

Is there any way of fixing this issue?

Rio
  • 595
  • 1
  • 6
  • 27

2 Answers2

1

It can be achieved using loop and subelements lookup/query, which is supported since version 2.5

- hosts: localhost
  vars:
    users:
      - name: 'share1'
        id: "{{'user1,user2,user3'.split(',')}}"
      - name: 'share2'
        id: "{{'user4'.split(',')}}"

  tasks:
  - name: Create users file with content
    copy:
      dest: "/etc/vsftpd_users/{{ item.1 }}"
      content: |
        local_root=/vol/{{ item.0.name }}
    loop: "{{lookup('subelements', users, 'id', skip_missing=True)}}"
Ignacio Millán
  • 7,480
  • 1
  • 25
  • 28
  • This worked perfectly @Ignacio. Thanks a lot. please just update `loop` with `with_list` as per the link you have shared. Using `loop` getting error. – Rio Oct 11 '18 at 14:33
  • You're welcome! That could happen because your ansible version, loop is a new feature of version 2.5 – Ignacio Millán Oct 11 '18 at 14:39
0

Ansible was not made to work with too complex data structure without scripting; To made it easy you shall restruct your user data as a list of dict with single ids like:

- name: Create users file with content
  copy:
  dest: "/etc/vsftpd_users/{{ item.id }}"
  content: |
    local_root=/vol/{{ item.name }}
  with_items:
  - { name: 'share1', id: 'user1' }
  - { name: 'share1', id: 'user2' }
  - { name: 'share1', id: 'user3' }
  - { name: 'share2', id: 'user4' }
Gabriel Pereira
  • 160
  • 1
  • 10
  • As per https://gist.github.com/angstwad/9893480 this should be possible. However now i am getting `'list object' has no attribute 'split'` – Rio Oct 11 '18 at 14:02
  • You will not be able to work with your data structure without using jina2 scripting. Ansible doesn't work with multiple activities per task. See an example here about dictionary iteraction: https://stackoverflow.com/questions/42167747/how-to-loop-over-this-dictionary-in-ansible – Gabriel Pereira Oct 11 '18 at 14:16