条件判断when:根据特定的条件来决定是否执行某个task。当条件为真时,任务将会执行;当条件为假时,任务将被跳过。
when关键字的使用非常简单,只需在单个任务的后面添加when条件判断语句即可。在when语句中,变量不需要使用{{ }}。
一.比较运算符 含义
> 大于
>= 大于等于
< 小于
<= 小于等于
== 等于
!= 不等于
二.逻辑运算符:用于组合多个条件。例如:
and:所有条件同时满足。例如:ansible_hostname == web01 and ansible_processor_cores == 2。
or:任一条件满足。例如:ansible_hostname == web01 or ansible_processor_cores == 2。
not:条件取反。例如:not ansible_hostname == web01。
三.正则表达式:用于匹配字符串模式。
案例1:判断远程主机的主机名是否为localhost,如果是创建文件
通过setup模块获取远程主机的信息
[root@ansible-server ~]# vim test_when.yml
- hosts: webserver
user: root
tasks:
- name: create file
file: path=/mnt/test1.txt state=touch #在执行上面的任务
register: create_file
when: ansible_hostname == "localhost" #先条件成立
- name: add 123 to file
shell: echo 123123 >> /mnt/test1.txt
- name: 打印过程
debug: msg={{ create_file }}
[root@ansible-server ~]# ansible-playbook test_when.yml
案例2:判断操作系统为centos安装nginx
ignore_errors: true #设置为true,如果命令1报错,也不影响其他命令执行
[root@ansible-server ~]# vim when_install.yml
- hosts: webserver
user: root
tasks:
- name: install package
ignore_errors: true
yum: name={{ 1 }} state=latest #记得替换变量item
loop:
- nginx
- redis
when: ansible_distribution == "CentOS"
- name: install epel
yum: name=epel-release state=latest
- name: create file
file: path=/root/ansible.txt state=touch
[root@ansible-server ~]# ansible-playbook when_install.yml
案例3:判断文件是否为空,如果是空那就添加内容
[root@ansible-server ~]# vim test_file.yml
- hosts: webserver
user: root
tasks:
- name: create file
file: path=/opt/file.txt state=touch
- name: Check if file is empty
shell: cat /opt/file.txt
register: check_file
- name: print vars
debug: msg={{ check_file }}
- name: insert hello
shell: echo "hello" >> /opt/file.txt
when: check_file.stdout == "" #字符串引号引起来
[root@ansible-server ~]# ansible-playbook test_file.yml
注意:
TASK [print vars] **************************************************************
ok: [192.168.229.158] => {
"msg": {
"changed": true,
"cmd": "cat /opt/file.txt",
"delta": "0:00:00.004283",
"end": "2023-07-30 01:28:32.812782",
"failed": false,
"rc": 0, #对于server可以作为判断依据,运行返回值为0,不运行返回值为非0
"start": "2023-07-30 01:28:32.808499",
"stderr": "",
"stderr_lines": [],
"stdout": "hello", #可以作为文件内容输出的判断依据
"stdout_lines": [
"hello"
]
}
}
案例4:判断mysql服务是否启动,没有启动那就启动
[root@ansible-server ~]# vim test_server.yml
- hosts: webserver
user: root
tasks:
- name: check mysql status
ignore_errors: true
shell: systemctl status mysqld
register: check_mysql
- name: print mysql server
debug:
var: check_mysql
- name: start mysqld
service: name=mysqld state=started
when: check_mysql.rc != 0
[root@ansible-server ~]# ansible-playbook test_server.yml