Search code examples
ansiblejinja2

ansible generate file loop dictionary


---
- name: main
  hosts: all
  become: true
  vars:
    sudoers_include:
      sudofile1:
          - "%kombit ALL=NOPASSWD: /usr/local/bin/create_sftp_dirs.sh"
          - "%kombit ALL=NOPASSWD: /usr/local/bin/add_public_key.sh"
          - "%kombit ALL=NOPASSWD: /usr/local/bin/remove_sftp_dirs.sh"
          - "%kombit ALL=NOPASSWD: /usr/local/bin/lock_file.sh"
          - "%kombit ALL=NOPASSWD: /usr/local/bin/unlock_file.sh"
      sudofile2:
          - "%admin1 ALL=NOPASSWD: /usr/local/bin/create_sftp_dirs.sh"
          - "%admin2 ALL=NOPASSWD: /usr/local/bin/add_public_key.sh"
  tasks:
  - copy:
     dest: "/tmp/{{item.key}}"
     content: |
          {%- for k,v in sudoers_include.items() -%}
              {% for c in v -%}
                {{c}}
              {% endfor -%}
          {%- endfor -%}
    loop: "{{ sudoers_include | dict2items }}"

However, this generate something like::

Either I\m using the wrong approach or I do miss something in defining the loop ?

 root@localhost:~# cat /tmp/sudofile1
 %kombit ALL=NOPASSWD: /usr/local/bin/create_sftp_dirs.sh
 %kombit ALL=NOPASSWD: /usr/local/bin/add_public_key.sh
 %kombit ALL=NOPASSWD: /usr/local/bin/remove_sftp_dirs.sh
 %kombit ALL=NOPASSWD: /usr/local/bin/lock_file.sh
 %kombit ALL=NOPASSWD: /usr/local/bin/unlock_file.sh
 %admin1 ALL=NOPASSWD: /usr/local/bin/create_sftp_dirs.sh
 %admin2 ALL=NOPASSWD: /usr/local/bin/add_public_key.sh

So, the idea is to generate the sudoers file... Don't know if the best approach would be templates or or the copy module ...


Solution

  • Q: "Would the best approach be templates or the copy module?"

    A: The only difference is the template in a file vs. in a block.


    Q: "Do I miss something in defining the loop?"

    A: The fixed template in the below content

        - copy:
            dest: "/tmp/{{ item.key }}"
            content: |
              {% for c in item.value %}
              {{ c }}
              {% endfor %}
          loop: "{{ sudoers_include|dict2items }}"
    

    gives

    shell> cat /tmp/sudofile1 
    %kombit ALL=NOPASSWD: /usr/local/bin/create_sftp_dirs.sh
    %kombit ALL=NOPASSWD: /usr/local/bin/add_public_key.sh
    %kombit ALL=NOPASSWD: /usr/local/bin/remove_sftp_dirs.sh
    %kombit ALL=NOPASSWD: /usr/local/bin/lock_file.sh
    %kombit ALL=NOPASSWD: /usr/local/bin/unlock_file.sh
    
    shell> cat /tmp/sudofile2
    %admin1 ALL=NOPASSWD: /usr/local/bin/create_sftp_dirs.sh
    %admin2 ALL=NOPASSWD: /usr/local/bin/add_public_key.sh