作者:mobiledu2502863117 | 来源:互联网 | 2023-08-11 14:38
我有一个由产品环境和开发环境组成的设置
有2个项目(project1和project2)
我有dev和ops用户。开发人员只能在分配了用户的项目中的开发服务器上创建,开发人员可以在所有项目和环境中创建操作。
我希望在同一用户定义文件中定义所有用户。
我的用户定义:
- username:
profile: # dev / ops
projects: # project1 / project2 / all
key: #"ssh-rsa key
OSgroups: "" # which OS groups is user member of
OSpass: "" # hashed OS password
我的用户创建剧本:
- name: Create users
become: yes
user:
name={{ item.username }}
shell={{ item.shell }}
groups={{ item.groups }}
createhome=yes
password={{ item.OSpass }}
## now the problem part
with_items:
- "{{ users }}"
when: "{{ defaults_for_env.environment }} == {{ item.profile }}"
##
------------------------------------------------------------
## environment defaults
---
defaults_for_env:
- environment: "dev"
仅在运行usercreate剧本用户时创建,因此命令有效。
我希望该剧本能够:
主机位于清单组[development]中,以创建分配给清单组[project1]和ops类型的所有用户的开发人员。
对于库存组[prod]中的主机,只能创建ops类型的用户。
我无法绕过循环和盘点东西
希望我的问题有意义吗?
一种解决当前需求的方法。
库存
---
all:
children:
dev:
hosts:
devhost1:
devhost2:
prod:
hosts:
prodhost1:
prodhost2
group_vars / all.yaml
---
#....
default_users:
- name: opsuser1
shell: /bin/bash
groups:
- group1
- group2
createhome: true
password: S0S3cr3t
- name: opsuser2
shell: /bin/sh
groups:
- wheel
- docker
- users
createhome: false
password: n0ts0S3cr3t
users: "{{ default_users + (specific_users | default([])) }}"
group_vars / dev.yml
---
#....
specific_users:
- name: devuser1
shell: /bin/bash
groups:
- groupa
- groupb
createhome: true
password: v3rYS3cr3t
- name: devuser2
shell: /bin/sh
groups:
- titi
- toto
- tata
createhome: false
password: U1trAS3cr3t
您的剧本
- hosts: all
become: true
tasks:
- name: Create users
user:
name: "{{ item.username }}"
shell: "{{ item.shell }}"
groups: "{{ item.groups }}"
createhome: "{{ item.createhome | bool }}"
password: ""{{ item.password | password_hash('sha512','S3cretS4lt') }}"
loop: "{{ users | flatten(levels=1) }}"
该剧本将遍历您的所有主机。默认情况下,它将读取all
组中的值,其中您具有default_users
的定义(即ops)+ users
列表的计算为default_users + specific_users
。>
对于prod
组中的计算机,specific_users
为null,默认为空列表。
对于dev
组中的计算机,specific_users
将被添加到默认计算机中。
然后在users
上进行循环,根据情况,每台机器将具有正确的值。