一 杂乱
官方
- shell: /usr/bin/foo
register: foo_result
ignore_errors: True
# ignore_errors 表示如果命令回传码如果是0,继续向下执行,不中断!
二 用户的创建
需求1:添加用户,不设置密码的形式
---
- hosts: test
tasks:
- name: create user
user:
name: "{{ item }}"
state: present
loop:
- wzj1
- wzj2
- wzj3
# 执行
ansible-playbook createuser.yml
# 结果
wzj1:x:1001:100::/home/wzj1:/bin/bash
wzj2:x:1002:100::/home/wzj2:/bin/bash
wzj3:x:1003:100::/home/wzj3:/bin/bash
需求2:用户设置相同的密码(密文)
---
- hosts: test
tasks:
- name: add several users
user:
name: "{{ item }}"
password: "{{ 'redhat'| password_hash('sha512') }}"
state: present
loop:
- wzj1
- wzj2
- wzj3
需求3:用户的密码均不一样
---
- hosts: test
tasks:
- name: add several users
user:
name: "{{ item.user }}"
password: "{{ 'item.pass'| password_hash('sha512') }}" # 注意单引号和双引号!
state: present
loop:
- { user: wzj1, pass: westos}
- { user: wzj2, pass: redhat}
- { user: wzj3, pass: wzj110}
说明:用户名与密码的键值对和创建用户的任务都写入同一个文件中,当要创建的用户很多时不易于我们检查,所以我们在生产环境中习惯将两者分开写,分别写入.yml文件中
需求4:优化
---
- hosts: test
vars_files:
- userlist.yml
tasks:
- name: add several users
user:
name: "{{ item.user }}"
password: "{{ item.pass| password_hash('sha512') }}"
state: present
loop: "{{ userlist }}"
userlist文件
---
# 密码:不要纯数字
userlist:
- user: wzj1
pass: wzj110
- user: wzj2
pass: wzj110
# 细节:密码引不引起来!
注意:一定要测试,是否可以登陆!