1.条件
等号后面是“字符串“,加引号
when:
条件1 and 条件2,或者:
- 条件1
- 条件2
“或者”:条件1 or 条件2
强调,以前写变量是这个格式"{{}}"
现在在when里是:
什么都不加
---
- name: test
hosts: prod
tasks:
- name: ping
shell:
ping -c1 -w1 172.25.250.90
register: prod
ignore_errors: yes
- debug:
msg: up host
when: prod.rc == 0
- debug:
msg: host is down
when: prod.rc !=0
检测90通不通,通的时候显示up host
不通显示 host is down
rc=0是ping通时的反馈
!=0(不等于)即不通时
---
- name: test
hosts: prod
tasks:
- debug:
msg: vdb exists
when: ansible_facts['devices']['vdc'] is defined
- debug:
msg: vdb dose not exist
when: ansible_facts['devices']['vdc'] is not defined
A is defined 变量存在
A is not defined 变量不存在
A is in B A变量为B
A is not in B A变量不为B
2.处理失败任务
(1).ignore_errors
如果不写,底下的就不会执行
(2) changed_when
changed_when: true
无论更改与否,都是为更改
(3)failed_when
当符合条件时强制任务失败
(4)
block:定义要运行的任务
rescue:定义当block句子中出现失败任务后运行的任务(当block出错后的排错)
always:定义最终独立运行的任务(一定要做的任务)
3.角色roles
角色是为了层次化,结构化的组织playbook
在企业复杂业务中应用场景很多
首先在私有化的ansible配置文件中书写roles的路径
roles_path=
然后需要创建相应的目录
[root@bastion ansible]# mkdir /home/devops/ansible/roles/
[root@bastion ansible]# ansible-galaxy list
# /home/devops/ansible/roles
这个命令可以查看roles的路径
[root@bastion ansible]# cd roles/
[root@bastion roles]# ansible-galaxy init apache
- Role apache was created successfully
在这个文件中配置apache
[root@bastion ansible]# ansible-galaxy list
# /home/devops/ansible/roles
- apache, (unknown version)
配置成功了
变量就往变量里写,tasks就往tasks里写
[root@bastion apache]# cd vars/
[root@bastion vars]# ls
main.yml
[root@bastion vars]# vim main.yml
tasks
vars
handlers
files
templates
执行方式:
[root@bastion ansible]# cat roles.yml
---
- name: test roles
hosts: prod
roles:
- apache
roles和playbook的区别是roles把playbook 的所有内容拆分开了,这样不用缩进,都是一级的
执行顺序:
(2)ansible-galaxy
是一个免费共享和下载ansibleroles的网站,可以帮助我们更好的定义和学习roles
官网是https://galaxy.ansible.com