ansibleactive-directoryusergroups

Is there a way to assign a user in the active directory to multiple groups with ansible?


I created an ansible-playbook which aims to add a user to a group in Active Directory via Ansible with code as shown below:

# addmembertogroup.yaml
# Skip task when 'group' or 'username' is undefined
# Show message when 'group' or 'username' doesn't exist
---
- hosts: brc.testlab.com
  gather_facts: no
  tasks:
    - name: "Add Member to Group"
      block:
        - name: "Add Member to Group"
          community.windows.win_domain_group_membership:
            name: "{{group}}"
            members: "{{username}}"
            state: present
          when: (group is defined) and (username is defined)
  
      rescue:
        - name: Print when error
          debug:
            msg: Username / Group not exist 

Where the playbook is run with the following command:

Ansible-playbook –i hosts addmembertogroup.yaml –e group=DNSAdmins –e username=Cahbayu

Based on the existing ansible playbook and command, I managed to add a user with the name Cahbayu into the DNSAdmins group. However, I want the user to be in multiple groups in one command. For example, I want to add user Cahbayu into the group DNSAdmins, Backup Operators, Remote Desktop Users. I've made the group parameters into a list like the following but the result still fail:

---
- hosts: brc.testlab.com
  gather_facts: no
  tasks:
    - name: "Add Member to Group"
      block:
        - name: "Add Member to Group"
          community.windows.win_domain_group_membership:
            name: 
              -  "{{group}}"
            members: "{{username}}"
            state: present
              when: (group is defined) and (username is defined)
  
          rescue:
            - name: Print when error
              debug:
                msg: Username / Group not exist 

And here's the result: [Failed to Add User to Multiple Groups][1]

Thus, my question is, is there a way to enter a user into multiple groups in Active Directory with Ansible? Thank you.


(Edited)

I managed to get user into multiple groups using ‘loop’ according to the answer provided.


Solution

  • I think you can manage to do so if you define the groups in a variable or a list and loop through the list that you want your user to be added in, check this this link it could help you manage doing it since your playbook is working and needs only a well defined loop

    https://docs.ansible.com/ansible/latest/user_guide/playbooks_loops.html[loops in ansible]1