问题描述
ashwani:present:super yashvinder:present:normal rajat:absent:super
注意:
解决方法
提供文件
shell> cat users.conf
ashwani:present:super yashvinder:present:normal rajat:absent:super
首先解析数据。例如
- set_fact:
my_users: "{{ my_users|default([]) +
[{'user': params.0,'state': params.1,'super': (params.2 == 'super')}] }}"
loop: "{{ lookup('file','users.conf').split(' ') }}"
vars:
params: "{{ item.split(':') }}"
- debug:
var: my_users
给予
"my_users": [
{
"state": "present","super": true,"user": "ashwani"
},{
"state": "present","super": false,"user": "yashvinder"
},{
"state": "absent","user": "rajat"
}
]
然后使用模块user创建用户。例如
- user:
name: "{{ item.user }}"
state: "{{ item.state }}"
loop: "{{ my_users }}"
使用lineinfile启用sudo。例如
- lineinfile:
path: /etc/sudoers
line: "{{ item.user }} ALL=(ALL) NOPASSWD: ALL"
loop: "{{ my_users }}"
when: item.super
(未测试)
,创建Ansible角色
$ ansible-galaxy init usermanagement
在角色任务文件中创建任务
$ vi usermanagement/tasks/main.yml
添加以下内容
---
# tasks file for createusers
- name: Create User
user:
name: "{{item.split(':').0}}"
state: "{{item.split(':').1}}"
loop: "{{ lookup('file','users.conf').splitlines() }}"
- name: Setup Sudo Access for Ansible User
copy:
dest: "/etc/sudoers.d/{{item.split(':').0}}"
content: "{{item.split(':').0}} ALL=(ALL) NOPASSWD: ALL"
validate: /usr/sbin/visudo -cf %s
loop: "{{ lookup('file','users.conf').splitlines() }}"
when: item.split(':').2 == "super" and item.split(':').1 == "present"
在具有以下内容的角色文件文件夹中创建users.conf(Meta)文件
ashwani:present:super
yashvinder:present:normal
rajat:absent:super
$ vi usermanagement/files/users.conf
创建一个主要的剧本并使用上面的角色。
$ vi main.yml
- hosts: all
become: true
roles:
- usersmanagement
执行主要剧本(具有主机清单)
$ ansible-playbook main.yml