在使用ansible做自动化运维的时候,大多数情况下都执行某些任务的时候都需要依赖某个变量的值或者是上一个任务的执行结果。如,根据facts信息中的系统版本相关的信息来确定使用哪种包管理器安装软件。Ansible提供when语句,可以控制任务的执行流程。
一个很简单的when语句的例子:
1 2 3 4 |
tasks: - name: "shutdown Debian flavored systems" command: / sbin / shutdown - t now when: ansible_os_family = = "Debian |
表示当节点主机系统为Debian的时候,执行关机操作。
在符合语句中也可以使用小括号:
1 2 3 4 5 |
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`语句中也可以使用过滤器。如,我们想跳过一个语句执行中的错误,但是后续的任务的执行需要由该任务是否成功执行决定:
1 2 3 4 5 6 7 8 9 10 |
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 |
有时候需要将一个字符串的变量转换为整数来进行数字比较:
1 2 3 |
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值决定是否执行该任务:
条件语句:
1 2 3 |
tasks: - shell: echo "This certainly is epic!" when: epic |
或:
1 2 3 |
tasks: - shell: echo "This certainly isn't epic!" when: not epic |
如果引用的变量没有被定义,使用Jinja2的`defined`测试,可以跳过或者是抛出错误:
1 2 3 4 5 6 |
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'"
|