应用场景:一般用于分发配置文件的时候.
如果配置文件发生变化则重启服务,如果没有变化则重启.
案例01: 没有使用触发器handlers
- hosts: web
gather_facts: no
tasks:
- name: 分发配置文件
copy:
src: exports
dest: /data/exports
backup: yes
notify:
- 重启服务
handlers:
- name: 重启服务
systemd:
name: nfs
state: reloaded
用于给ans运行的task(模块)设置条件,满足或不满足条件在运行对应的模块.
应用建议: when进行判断,一般与变量一起使用.
when条件一般与facts变量或register变量一起使用.
案例02 : 如果系统是centos则 安装sl,cowsay,如果是ubuntu 则安装cmatrix
- hosts: all
tasks:
- name: yum sl,cowsay
yum:
name: sl,cowsay
state: installed
when: ansible_distribution == "CentOS"
- name: apt cmatrix
apt:
name: cmatrix
state: present
when: ansible_distribution == "Ubuntu"
loop 批量创建文件,批量添加用户,批量启动或重启服务.
案例03: 批量启动服务 rpcbind 然后 nfs服务
- hosts: nfs
gather_facts: no
tasks:
- name: 重启rpcbind,nfs
systemd:
name: "{{ item }}"
state: restarted
loop:
- rpcbind
- nfs
案例04 循环创建用户指定UID
hosts: all
gather_facts: no
tasks:
- name: add user
user:
shell: /bin/bash
name: "{{ item.name }}"
uid: "{{ item.uid }}"
state: present
loop:
- { name: 'oldboy', uid: 2020 }
- { name: 'lidao', uid: 2021 }
- { name: 'lidao996', uid: 2022 }
-C --check 模拟运行,不作出改变,一些变量可能会提示报错,因为-C没有真正运行剧本
--syntax-check 只做语法检查,不运行.
高级: step 单步运行. y执行这个task,n忽略这个task,c自动运行
tag标签类似于超市物品的分类,只不过tag标签是给ansible中的task进行分类.加上标记
运行剧本的时候运行指定的tag标签或排除某些tag.
ansible-playbook -i hosts -t 04.start srv 14.deploy-nfs-tag.yml
运行剧本的时候,因为重复运行导致的错误提示,并发是真的错误.
比如:目录已经存在,用户已经存在. 在这种情况下,我们可以通过ignore_errors忽略错误,让剧本可以继续运行.
ignore_errors: true
template模块与xxx.j2文件
应用场景:
1、进行分发配置文件或文件的时候,需要在文件中使用变量,需要使用jinja2文件 nginx.conf.j2,需要使用template模块进行分发.
2、进行判断
3、进行循环
- hosts: all
gather_facts: no
tasks:
- name: 分发motd文件
template:
src: templates/motd.j2
dest: /etc/motd
backup: yes
- name: 分发motd文件
copy:
src: templates/motd.j2
dest: /tmp/motd
backup: yes
四、include文件包含
day42暂不更新,赶进度~~~