ARTICLE · INTELLIGENCE

战地情报 · 详情页

来自尧图项目组的一线实战观察与深度解析

3-ansible关键字when

3-ansible关键字when 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 == trueORwhen: 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
RELATED READING

延伸阅读

更多一线实战笔记与深度复盘,助您持续精进