When 语句
有时您会想要跳过特定主机上的特定步骤。 如果操作系统是特定版本,这可能是一个简单的方法,如果没有安装某个包,或者如果文件系统正在充满,可能会执行一些清理步骤。
这在使用when子句时很容易做到,它包含一个没有双大括号的原始Jinja2表达式(见变量 )。 其实很简单:
tasks: - name: "shut down Debian flavored systems"
command: /sbin/shutdown -t now
when: ansible_os_family == "Debian"
# note that Ansible facts and vars like ansible_os_family can be used
# directly in conditionals without double curly braces
您也可以使用括号来分组条件:
tasks: - name: "shut down CentOS 6 and Debian 7 systems"
command: /sbin/shutdown -t now
when: (ansible_distribution == "CentOS" and ansible_distribution_major_version == "6") or
(ansible_distribution == "Debian" and ansible_distribution_major_version == "7") 所有需要为真的多个条件(逻辑“和”)也可以指定为列表:
tasks: - command: /bin/false
register: result
ignore_errors: True
- command: /bin/something
when: result|failed
# In older versions of ansible use |success, now both are valid but succeeded uses the correct tense.
- command: /bin/something_else
when: result|succeeded
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中定义的变量。 一个例子可能是基于一个变量的布尔值执行一个任务:
vars: epic: true
那么条件执行可能如下所示:
tasks: - shell: echo "This certainly is epic!"
when: epic
# for facter
ansible -m yum -a "pkg=facter state=present"
ansible -m yum -a "pkg=ruby-json state=present"
# for ohai
ansible -m yum -a "pkg=ohai state=present"
可配置的配置方法 - 将变量与任务分离,使您的剧本不会变成具有丑陋的嵌套ifs,条件等的任意代码,并导致更精简和可审计的配置规则,特别是因为至少有一个决策点要跟踪。
Selecting Files And Templates Based On Variables
有时您要复制的配置文件或您将使用的模板可能取决于变量。 以下构造选择适合于给定主机的变量的第一个可用文件,这通常比在模板中放入大量条件更为干净。
以下示例显示如何模板化出与CentOS和Debian之间有很大不同的配置文件: