ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
这个when应该不能算是一个[模块][1] Ansible提供when语句,可以控制任务的执行流程。 一个很简单的when语句的例子 ~~~ tasks: - name: "shutdown Debian flavored systems" command: /sbin/shutdown -t now when: ansible_os_family == "Debian ~~~ 在符合语句中也可以使用小括号: ~~~ tasks: - name: "shutdown CentOS 6 and 7 systems" command: /sbin/shutdown -t now when: ansible_distribution == "CentOS" and (ansible_distribution_major_version == "6" or ansible_distribution_major_version == "7") ~~~ 在`when`语句中也可以使用过滤器。如,我们想跳过一个语句执行中的错误,但是后续的任务的执行需要由该任务是否成功执行决定: ~~~ tasks: - command: /bin/false register: result ignore_errors: True - command: /bin/something when: result|failed - command: /bin/something_else when: result|success - command: /bin/still/something_else when: result|skipped ~~~ 有时候需要将一个字符串的变量转换为整数来进行数字比较: ~~~ tasks: - shell: echo "only on Red Hat 6, derivatives, and later" when: ansible_os_family == "RedHat" and ansible_lsb.major_release|int >= 6 ~~~ 在playbooks和inventory中定义的变量都可以使用,如,需要根据一个变量的bool值决定是否执行该任务: ~~~ vars: epic: true ~~~ 条件语句: ~~~ tasks: - shell: echo "This certainly is epic!" when: epic ~~~ ~~~ tasks: - shell: echo "This certainly isn't epic!" when: not epic ~~~ 如果引用的变量没有被定义,使用Jinja2的`defined`测试,可以跳过或者是抛出错误: ~~~ tasks: - shell: echo "I've got '{{ foo }}' and am not afraid to use it!" when: foo is defined - fail: msg="Bailing out. this play requires 'bar'" when: bar is not defined ~~~ [1]:http://docs.ansible.com/ansible/latest/playbooks_conditionals.html#the-when-statement