Home > OS >  Ansible jinja dictionary create multiple sudo files for each user
Ansible jinja dictionary create multiple sudo files for each user

Time:01-09

I'm trying to create a sudo file for each user.

Playbook:

- name:
  hosts: all
  gather_facts: false
  tasks:
    - name:
      template:
        src: sudo.j2
        dest: "/etc/sudoers.d/{{item.name}}"
      loop: "{{userinfo}}"
      when: "'admins' in item.groupname"

Var file:

userinfo:
  - groupname: admins
    name: bill
  - groupname: admins
    name: bob
  - groupname: devs
    name: bea

Jinja file:

{% for item in userinfo %}
{% if item.groupname=="admins" %}
{{item.name}} ALL=ALL NOPASSWD:ALL
{% endif %}
{% endfor %}

What I am getting is two files but with information of both users.

bill ALL=ALL NOPASSWD:ALL
bob ALL=ALL NOPASSWD:ALL

How do I make it work such that each file contains information of that user only

CodePudding user response:

The issue is that you have 2 loops: one in the playbook, the other in the template jinja file; try leaving the template file with the templated information only

{{ item.name }} ALL=ALL NOPASSWD:ALL
  • Related