在Ansible中根据组更改哪些用户创build的variables

我有以下任务

- name: Create users user: uid: "{{ item.uid }}" name: "{{ item.username }}" comment: "{{ item.comment }}" shell: /bin/bash groups: "{{ item.groups }}" with_items: users 

users包含在公司工作的所有用户,我想在samba服务器上创build所有用户。 但也有3个pipe理员,我只想在不在samba组中的其他服务器上创build它们。

我可以使用上面的方法创buildpipe理员用户,如果我when: item.username in admin_users添加when: item.username in admin_users ,但是会为所有用户执行此操作,并且我希望新服务器的默认值仅用于创buildadmin_users,但是如果服务器处于桑巴集团,创build所有的用户。

会有一个简单的方法来做到这一点? 我正在考虑将用户分成两组,并通过运行两个任务来创buildadmin_user和other_users,但是我想知道是否有针对此问题的DRY解决scheme。

playbook.yml

 --- - hosts: all gather_facts: no vars: users: - { uid: user1, username: username1, comment: comment1, shell: /bin/bash, groups: group1 } - { uid: user2, username: username2, comment: comment2, shell: /bin/bash, groups: group2 } admin_users: [ username1 ] users_admin: | {%- set o=[] %} {%- for i in users %} {%- if i.username in admin_users %} {%- if o.append(i) %} {%- endif %} {%- endif %} {%- endfor %} {{ o }} users_filtered: "{{ users if 'samba' in group_names else users_admin }}" tasks: - debug: var: users_filtered 

主机

 host1 ansible_ssh_host=localhost [samba] host2 ansible_ssh_host=localhost 

示例会话:

 $ ansible-playbook -i hosts playbook.yml PLAY [all] ******************************************************************** TASK: [debug ] **************************************************************** ok: [host1] => { "var": { "users_filtered": [ { "comment": "comment1", "groups": "group1", "shell": "/bin/bash", "uid": "user1", "username": "username1" } ] } } ok: [host2] => { "var": { "users_filtered": [ { "comment": "comment1", "groups": "group1", "shell": "/bin/bash", "uid": "user1", "username": "username1" }, { "comment": "comment2", "groups": "group2", "shell": "/bin/bash", "uid": "user2", "username": "username2" } ] } } PLAY RECAP ******************************************************************** host1 : ok=1 changed=0 unreachable=0 failed=0 host2 : ok=1 changed=0 unreachable=0 failed=0