Ansible自动化之批量创建用户

[Ansible自动化]之批量创建用户


Ansible中文权威指南 Ansible
Ansible-Playbooks中文指南 Ansible-Playbooks


剧本正文

请注意:(以下剧本存在一些变量,请根据实际情况使用或修改,请根据YML格式进行修改)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
---
- name: Initialize the security of Changan Linux system
hosts: "{{ hosts }}"
remote_user: "{{ user }}"
sudo: yes
vars:
user1: user1
user2: user2
tasks:

- name: Create user {{ user1 }}
user:
name: "{{ user1 }}"
shell: /bin/bash
createhome: yes
home: /home/{{ user1 }}
state: present

- name: Create user {{ user2 }}
user:
name: "{{ user2 }}"
shell: /bin/bash
createhome: yes
home: /home/{{ }}
state: present


- name: Set authorized key taken {{ user1 }}
authorized_key:
user: "{{ user1 }}"
state: present
key: "{{ lookup('file', '/etc/ansible/keys/ssh/user1_id_rsa.pub') }}"

- name: Set authorized key taken {{ user2 }}
authorized_key:
user: "{{ user2 }}"
state: present
key: "{{ lookup('file', '/etc/ansible/keys/ssh/user2_id_rsa.pub') }}"



- name: Allow {{ user1 }} to have passwordless sudo
lineinfile:
dest: /etc/sudoers
state: present
line: "{{ user1 }} ALL=(ALL) NOPASSWD: ALL"

- name: Allow {{ user2 }} to have passwordless sudo
lineinfile:
dest: /etc/sudoers
state: present
line: "{{ user2 }} ALL=(ALL) NOPASSWD: ALL"

剧本详情讲解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
---
- name: Initialize the security of Changan Linux system
hosts: "{{ hosts }}" #执行任务的目标主机
remote_user: "{{ user }}" #在目标主机上执行任务的用户
sudo: yes #使用sudo执行命令
vars: #剧本定义变量
user1: user1
user2: user2
tasks: #任务列表

- name: Create user {{ user1 }} #创建用户
user:
name: "{{ user1 }}" #用户名
shell: /bin/bash #系统环境
createhome: yes #是否创建home下目录
home: /home/{{ user1 }} #宿主目录
state: present

- name: Create user {{ user2 }}
user:
name: "{{ user2 }}"
shell: /bin/bash
createhome: yes
home: /home/{{ }}
state: present


- name: Set authorized key taken {{ user1 }} #传输SSH公钥(用于SSH秘钥连接)
authorized_key:
user: "{{ user1 }}" #用户名
state: present
key: "{{ lookup('file', '/etc/ansible/keys/ssh/user1_id_rsa.pub') }}" #公钥地址

- name: Set authorized key taken {{ user2 }}
authorized_key:
user: "{{ user2 }}"
state: present
key: "{{ lookup('file', '/etc/ansible/keys/ssh/user2_id_rsa.pub') }}"



- name: Allow {{ user1 }} to have passwordless sudo #赋予sudo权限
lineinfile:
dest: /etc/sudoers
state: present
line: "{{ user1 }} ALL=(ALL) NOPASSWD: ALL" #赋予所以权限,使用sudo不需要密码

- name: Allow {{ user2 }} to have passwordless sudo
lineinfile:
dest: /etc/sudoers
state: present
line: "{{ user2 }} ALL=(ALL) NOPASSWD: ALL"

More Info: Ansible