共计 2011 个字符,预计需要花费 6 分钟才能阅读完成。
编辑存放用户名和密码的.yml 文件
vim userlist.yml
---
userlist:
- user: user1
pass: '123'
- user: user2
pass: '456'
- user: user3
pass: '789'
编辑创建用户的.yml 文件
[root@az-mq-001 ansible]# cat createuser.yml
---
- hosts: webserver
vars_files:
- userlist.yml
tasks:
- name: create user
user:
name: "{{item.user}}"
password: "{{item.pass | password_hash('sha512') }}"
state: present
loop: "{{userlist}}"
对存放用户名和密码的.yml 文件进行加密,并输入密码:
ansible-vault encrypt userlist.yml
cat 结果如下
[root@az-mq-001 ansible]# cat userlist.yml
$ANSIBLE_VAULT;1.1;AES256
62623438393233643663656630326362363637376435363965306362373564366632343738346464
6339316664366234353739313235313864326561343638320a393035626432336266376366313130
38326666613937396263336431633161623061393839646462656562636362373131633335396265
3962336630643765390a303631396165313332646135636638646336303463633561616331376161
63373165656434616630303030623138626161613039656566613039323637356539326336386664
65623563306430356566393238363666346361333061396636633734353634333731636430626234
34313831643566663966363430653966623334326332346138306639643365633533303661353262
37623164613861363762313135623864616366303965393335333332656238396362313134383365
34663163383162616461386161363664656463653061373230616361643235333765
查看加密后的文件内容(注意需要输入密码)
如果需要编辑使用命令
ansible-vault edit userlist.yml
[root@az-mq-001 ansible]# ansible-vault view userlist.yml
Vault password:
---
userlist:
- user: user1
pass: '123'
- user: user2
pass: '456'
- user: user3
pass: '789'
使用加密的方式创建用户
ansible-playbook createuser.yml --ask-vault-pass
验证时可以使用 ssh 或者直接 cat ./etc/passwd
user1:x:1001:1001::/home/user1:/bin/bash
user2:x:1002:1002::/home/user2:/bin/bash
user3:x:1003:1003::/home/user3:/bin/bash
踩坑日志:
注意 yml 文件的格式需要先验证,格式空格都要对,不然会报错。
我遇到的报错如下
fatal: [192.168.0.91]: FAILED! => {“msg”: “Invalid data passed to ‘loop’, it requires a list, got this instead: { { (userlist, wantlist=True) }}. Hint: If you passed a list/dict of just one element, try adding wantlist=True to your lookup invocation or use q/query instead of lookup.”}
解决办法
参考的教程时别人的格式有问题,这几个写到一行就好了。
- name: create user
user:
name: "{{item.user}}"
password: "{{item.pass | password_hash('sha512') }}"
state: present
loop: "{{userlist}}"
正文完