[devops@server1 ansible]$ touch createuser.yml
[devops@server1 ansible]$ vim createuser.yml
---
- hosts: test
tasks:
- name: create user
user:
name: "{{ item }}" #循环 添加user1~3
state: present
loop:
- user1
- user2
- user3
[devops@server1 ansible]$ ansible-playbook createuser.yml
[root@server2 ~]# cat /etc/shadow
密码为明文形式,不安全。
方法一:全部写入createuser.yml文件中。
[devops@server1 ansible]$ vim createuser.yml
---
- hosts: test
tasks:
- name: create user
user:
name: "{{ item.user }}"
password: "{{ 'item.pass' | password_hash('sha512') }}" #采用哈希加密
state: present
loop:
- { user: user1, pass: 123}
- { user: user2, pass: 456}
- { user: user3, pass: 789}
执行:
[devops@server1 ansible]$ ansible-playbook createuser.yml
[root@server2 ~]# cat /etc/shadow
方法二:将要添加的用户和要执行的任务分开写:
[devops@server1 ansible]$ vim userlist.yml
---
userlist:
- user: user1
pass: 123
- user: user2
pass: 456
- user: user3
pass: 789
[devops@server1 ansible]$ vim createuser.yml
---
- hosts: test
vars_files:
- userlist.yml #用户名和密码的文件,在同一个目录下
tasks:
- name: create user
user:
name: "{{ item.user }}"
password: "{{ 'item.pass' | password_hash('sha512') }}"
state: present
loop: "{{ userlist }}"
执行:
[devops@server1 ansible]$ ansible-playbook createuser.yml
[devops@server1 ansible]$ ansible-vault
Usage: ansible-vault [create|decrypt|edit|encrypt|encrypt_string|rekey|view] [options] [vaultfile.yml] 加密 编辑 查看 为几个常用的方法
[devops@server1 ansible]$ vim userlist.yml
---
userlist:
- user: user1
pass: '123'
- user: user2
pass: '456'
- user: user3
pass: '789' #密码都引起来,字符串
[devops@server1 ansible]$ vim createuser.yml
---
- hosts: test
vars_files:
- userlist.yml
tasks:
- name: create user
user:
name: "{{ item.user }}"
password: "{{ item.pass | password_hash('sha512') }}" #不引
state: present
loop: "{{ userlist }}"
[devops@server1 ansible]$ ansible-vault encrypt userlist.yml
[devops@server1 ansible]$ cat userlist.ym
[devops@server1 ansible]$ ansible-vault view userlist.yml
[devops@server1 ansible]$ ansible-vault edit userlist.yml
---
userlist:
- user: user1
pass: '123'
- user: user2
pass: '456'
- user: user3
pass: '789'
- user: user4 #加入
pass: 'westos'
[devops@server1 ansible]$ ansible-vault view userlist.yml
[devops@server1 ansible]$ ansible-playbook createuser.yml --ask-vault-pass
[root@server2 ~]# cat /etc/shadow
[devops@server1 ansible]$ ssh user1@server2
[user1@server2 ~]$ su - user4