我有以下任务
- name: Create users
user:
uid: "{{ item.uid }}"
name: "{{ item.username }}"
comment: "{{ item.comment }}"
shell: /bin/bash
groups: "{{ item.groups }}"
with_items: users
users
包含公司内所有工作的用户,我想在 Samba 服务器上创建所有这些用户。但还有 3 个管理员,我只想在不属于 Samba 组的其他服务器上创建他们。
如果我添加,我可以使用上述内容创建管理员用户
when: item.username in admin_users
,但这将为所有用户执行此操作,并且我希望新服务器的默认设置是仅创建 admin_users,但如果服务器在 samba 组中,则创建所有用户。
有没有简单的方法可以做到这一点?我正在考虑将用户分成两组,并通过运行两个任务来创建 admin_user 和 other_users,但我想知道是否有针对此问题的 DRY 解决方案。
答案1
剧本.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