2.1 问题
本案例要求熟悉playbook进阶:
练习使用user模块添加用户
练习使用变量简化task,让play通用性更强
练习使用过滤器
2.2 步骤
实现此案例需要按照如下步骤进行。
步骤一:使用user模块添加用户,并修改密码
[root@ansible ansible]# vim user.yml
- hosts: cache
remote_user: root
vars:
username: xiaoming
tasks:- name: create user “{{username}}”
user: group=wheel uid=1000 name={{username}} - shell: echo 123456 | passwd --stdin xiaoming
- shell: chage -d 0 {{username}}
[root@ansible ansible]# ansible-playbook user.yml //执行结果
PLAY [cache] ******************************************************************
TASK [Gathering Facts] ********************************************************
ok: [cache]
TASK [create user " xiaoming "] ***********************************************
changed: [cache]
TASK [command] ****************************************************************
changed: [cache]
TASK [command] ****************************************************************
changed: [cache]
PLAY RECAP ********************************************************************
cache : ok=4 changed=3 unreachable=0 failed=0
步骤二:变量过滤器,创建一个用户,设置密码
- name: create user “{{username}}”
[root@ansible ansible]# vim user1.yml
- hosts: cache
remote_user: root
tasks:- user:
name: lisi
group: root
password: “{{‘123456’ | password_hash(‘sha512’)}}” - shell: chage -d 0 lisi
[root@ansible ansible]# ansible-playbook user1.yml
PLAY [cache] ******************************************************************
TASK [Gathering Facts] ********************************************************
ok: [cache]
TASK [user] *******************************************************************
changed: [cache]
TASK [command] ****************************************************************
changed: [cache]
PLAY RECAP ********************************************************************
cache : ok=3 changed=2 unreachable=0 failed=0
步骤三:定义一个变量创建用户
- user:
[root@ansible ansible]# vim user2.yml
- hosts: cache
remote_user: root
vars:
user: zhangs
tasks:- user:
name: “{{user}}”
group: root
password: “{{‘123456’ | password_hash(‘sha512’)}}” - shell: chage -d 0 “{{user}}”
[root@ansible ansible]# ansible-playbook user2.yml
PLAY [cache] ******************************************************************
TASK [Gathering Facts] ********************************************************
ok: [cache]
TASK [user] *******************************************************************
changed: [cache]
TASK [command] ****************************************************************
changed: [cache]
PLAY RECAP ********************************************************************
cache : ok=3 changed=2 unreachable=0 failed=0
- user: