when是ansible playbook中最常用的条件判断关键字,用于决定某个任务(task)、block、role或include_tasks是否执行。它的作用类似于编程语言中的if。
1.基本语法
- hosts: all tasks: - name: Install httpd yum: name: httpd state: present when: ansible_os_family == "RedHat"备注:只有当目标主机的ansible_os_family等于“RedHat”时,才执行安装httpd。
[root@cent79-2 yaml-directory]# ansible-playbook-2 when.yaml PLAY [all] **************************************************************************************************** TASK [Gathering Facts] **************************************************************************************** ok: [192.168.10.100] TASK [Install httpd] ****************************************************************************************** ok: [192.168.10.100] PLAY RECAP **************************************************************************************************** 192.168.10.100 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 [root@cent79-2 yaml-directory]#2.when可以判断的内容
1.判断变量
- hosts: all vars: install_httpd: true tasks: - name: Install httpd yum: name: httpd state: present when: install_httpd变量(install_httpd)为true-->执行
变量(install_httpd)为false-->跳过
上述when条件也可以使用如下方式
when: install_httpd == trueOR
when: install_httpd | bool2.判断字符串
- hosts: all tasks: - name: Install httpd yum: name: httpd state: present when: ansible_os_family == "RedHat"结果:
[root@cent79-2 yaml-directory]# ansible-playbook-2 when.yaml PLAY [all] **************************************************************************************************** TASK [Gathering Facts] **************************************************************************************** ok: [192.168.10.100] TASK [Install httpd] ****************************************************************************************** ok: [192.168.10.100] PLAY RECAP **************************************************************************************************** 192.168.10.100 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0 [root@cent79-2 yaml-directory]#3.判断数字
- hosts: all tasks: - name: Install httpd yum: name