条件语句
在剧本中,您可能希望根据事实(有关远程系统的
Ansible 在条件语句中使用 Jinja2 测试
注意
在 Ansible 中控制执行流程有很多选项。您可以在
使用 when
的基本条件语句
最简单的条件语句应用于单个任务。创建任务,然后
tasks:
- name: Configure SELinux to start mysql on any port
ansible.posix.seboolean:
name: mysql_connect_any
state: true
persistent: true
when: ansible_selinux.status == "enabled"
# all variables can be used directly in conditionals without double curly braces
基于 ansible_facts 的条件语句
通常,您希望根据事实执行或跳过任务。事实
您可以在操作系统是特定版本时仅安装
您可以在具有内部 IP 地址的主机上跳过
您可以在文件系统即将满时执行清理任务。
请参见 常用事实
- name: Show facts available on the system
ansible.builtin.debug:
var: ansible_facts
以下是一个基于事实的条件语句示例
tasks:
- name: Shut down Debian flavored systems
ansible.builtin.command: /sbin/shutdown -t now
when: ansible_facts['os_family'] == "Debian"
如果有多个条件,您可以使用括号将它们分组
tasks:
- name: Shut down CentOS 6 and Debian 7 systems
ansible.builtin.command: /sbin/shutdown -t now
when: (ansible_facts['distribution'] == "CentOS" and ansible_facts['distribution_major_version'] == "6") or
(ansible_facts['distribution'] == "Debian" and ansible_facts['distribution_major_version'] == "7")
您可以使用 逻辑运算符
tasks:
- name: Shut down CentOS 6 systems
ansible.builtin.command: /sbin/shutdown -t now
when:
- ansible_facts['distribution'] == "CentOS"
- ansible_facts['distribution_major_version'] == "6"
如果事实或变量是字符串,并且您需要对它执行
tasks:
- ansible.builtin.shell: echo "only on Red Hat 6, derivatives, and later"
when: ansible_facts['os_family'] == "RedHat" and ansible_facts['lsb']['major_release'] | int >= 6
您可以将 Ansible 事实存储为变量以用于条件
tasks:
- name: Get the CPU temperature
set_fact:
temperature: "{{ ansible_facts['cpu_temperature'] }}"
- name: Restart the system if the temperature is too high
when: temperature | float > 90
shell: "reboot"
基于已注册变量的条件语句
通常,您希望根据先前任务的结果执行或跳过
将先前任务的结果注册为变量。
创建基于已注册变量的条件测试。
使用 register
关键字创建已注册变量的
- name: Test play
hosts: all
tasks:
- name: Register a variable
ansible.builtin.shell: cat /etc/motd
register: motd_contents
- name: Use the variable in conditional statement
ansible.builtin.shell: echo "motd contains the word hi"
when: motd_contents.stdout.find('hi') != -1
如果变量是列表,您可以在任务的循环中使用已
- name: Registered variable usage as a loop list
hosts: all
tasks:
- name: Retrieve the list of home directories
ansible.builtin.command: ls /home
register: home_dirs
- name: Add home dirs to the backup spooler
ansible.builtin.file:
path: /mnt/bkspool/{{ item }}
src: /home/{{ item }}
state: link
loop: "{{ home_dirs.stdout_lines }}"
# same as loop: "{{ home_dirs.stdout.split() }}"
已注册变量的字符串内容可能是空的。如果希望
- name: check registered variable for emptiness
hosts: all
tasks:
- name: List contents of directory
ansible.builtin.command: ls mydir
register: contents
- name: Check contents for emptiness
ansible.builtin.debug:
msg: "Directory is empty"
when: contents.stdout == ""
Ansible 始终在已注册变量中为每个主机注册
tasks:
- name: Register a variable, ignore errors and continue
ansible.builtin.command: /bin/false
register: result
ignore_errors: true
- name: Run only if the task that registered the "result" variable fails
ansible.builtin.command: /bin/something
when: result is failed
- name: Run only if the task that registered the "result" variable succeeds
ansible.builtin.command: /bin/something_else
when: result is succeeded
- name: Run only if the task that registered the "result" variable is skipped
ansible.builtin.command: /bin/still/something_else
when: result is skipped
- name: Run only if the task that registered the "result" variable changed something.
ansible.builtin.command: /bin/still/something_else
when: result is changed
注意
Ansible 的早期版本使用 success
和
基于变量的条件语句
您还可以创建基于在剧本或清单中定义的变量
vars:
epic: true
monumental: "yes"
使用上面的变量,Ansible 将运行以下任务之一,
tasks:
- name: Run the command if "epic" or "monumental" is true
ansible.builtin.shell: echo "This certainly is epic!"
when: epic or monumental | bool
- name: Run the command if "epic" is false
ansible.builtin.shell: echo "This certainly isn't epic!"
when: not epic
如果未设置所需的变量,您可以使用 Jinja2 的
tasks:
- name: Run the command if "foo" is defined
ansible.builtin.shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
when: foo is defined
- name: Fail if "bar" is undefined
ansible.builtin.fail: msg="Bailing out. This play requires 'bar'"
when: bar is undefined
这在结合 vars
文件的条件导入(
在循环中使用条件语句
如果将 when
语句与
tasks:
- name: Run with items greater than 5
ansible.builtin.command: echo {{ item }}
loop: [ 0, 2, 4, 6, 8, 10 ]
when: item > 5
如果需要在循环变量未定义时跳过整个任务,
- name: Skip the whole task when a loop variable is undefined
ansible.builtin.command: echo {{ item }}
loop: "{{ mylist|default([]) }}"
when: item > 5
在循环遍历字典时,您可以执行相同的操作
- name: The same as above using a dict
ansible.builtin.command: echo {{ item.key }}
loop: "{{ query('dict', mydict|default({})) }}"
when: item.value > 5
加载自定义事实
您可以提供自己的事实,如
tasks:
- name: Gather site specific fact data
action: site_facts
- name: Use a custom fact
ansible.builtin.command: /usr/bin/thingy
when: my_custom_fact_just_retrieved_from_the_remote_system == '1234'
使用重复的条件语句
您可以在可重用任务文件、剧本或角色中使用条件语句。Ansible 对动态重用(包含)和静态重用(导入)以不同的方式执行这些条件语句。有关 Ansible 中重用的更多信息,请参见 重用 Ansible 工件。
使用导入的条件语句
当您在导入语句中添加条件语句时,Ansible 会将该条件应用于导入文件中所有任务。此行为等效于 标签继承:将标签添加到多个任务。Ansible 会将条件应用于每个任务,并分别评估每个任务。例如,如果您想定义并显示一个以前未定义的变量,您可能有一个名为 main.yml
的剧本和一个名为 other_tasks.yml
的任务文件。
# all tasks within an imported file inherit the condition from the import statement
# main.yml
- hosts: all
tasks:
- import_tasks: other_tasks.yml # note "import"
when: x is not defined
# other_tasks.yml
- name: Set a variable
ansible.builtin.set_fact:
x: foo
- name: Print a variable
ansible.builtin.debug:
var: x
Ansible 在执行时将其扩展为以下等效代码:
- name: Set a variable if not defined
ansible.builtin.set_fact:
x: foo
when: x is not defined
# this task sets a value for x
- name: Do the task if "x" is not defined
ansible.builtin.debug:
var: x
when: x is not defined
# Ansible skips this task, because x is now defined
如果 x
最初已定义,则两个任务都将按预期跳过。但如果 x
最初未定义,则调试任务将被跳过,因为条件针对每个导入的任务进行评估。条件将对 set_fact
任务评估为 true
,这将定义变量并导致 debug
条件评估为 false
。
如果这不是您想要的行为,请使用 include_*
语句,仅将条件应用于该语句本身。
# using a conditional on include_* only applies to the include task itself
# main.yml
- hosts: all
tasks:
- include_tasks: other_tasks.yml # note "include"
when: x is not defined
现在,如果 x
最初未定义,则调试任务不会被跳过,因为条件在包含时进行评估,并且不适用于各个任务。
您也可以对 import_playbook
以及其他 import_*
语句应用条件。当您使用这种方法时,Ansible 会对不符合条件的每个主机上的每个任务返回一个“跳过”消息,从而生成重复的输出。在许多情况下,group_by 模块 可以作为一种更简化的方式来实现相同目标;请参见 处理 OS 和发行版差异。
使用包含的条件语句
当您在 include_*
语句上使用条件语句时,条件仅应用于包含任务本身,而不应用于包含文件中的任何其他任务。为了与上面用于导入条件语句的示例形成对比,请查看相同的剧本和任务文件,但使用包含而不是导入。
# Includes let you reuse a file to define a variable when it is not already defined
# main.yml
- include_tasks: other_tasks.yml
when: x is not defined
# other_tasks.yml
- name: Set a variable
ansible.builtin.set_fact:
x: foo
- name: Print a variable
ansible.builtin.debug:
var: x
Ansible 在执行时将其扩展为以下等效代码:
# main.yml
- include_tasks: other_tasks.yml
when: x is not defined
# if condition is met, Ansible includes other_tasks.yml
# other_tasks.yml
- name: Set a variable
ansible.builtin.set_fact:
x: foo
# no condition applied to this task, Ansible sets the value of x to foo
- name: Print a variable
ansible.builtin.debug:
var: x
# no condition applied to this task, Ansible prints the debug statement
通过使用 include_tasks
而不是 import_tasks
,other_tasks.yml
中的两个任务将按预期执行。有关 include
与 import
之间差异的更多信息,请参见 重用 Ansible 工件。
使用角色的条件语句
有三种方法可以将条件应用于角色。
通过将
when
语句放在roles
关键字下,将相同的条件或条件添加到角色中的所有任务。请参见本节中的示例。通过将
when
语句放在剧本中的静态import_role
上,将相同的条件或条件添加到角色中的所有任务。将条件或条件添加到角色本身内的单个任务或块。这是唯一一种允许您根据
when
语句选择或跳过角色中某些任务的方法。要选择或跳过角色内的任务,您必须在单个任务或块上设置条件,在剧本中使用动态include_role
,并将条件或条件添加到包含中。当您使用这种方法时,Ansible 会将条件应用于包含本身以及角色中也具有该when
语句的任何任务。
当您使用 roles
关键字在剧本中静态包含角色时,Ansible 会将您定义的条件添加到角色中的所有任务。例如:
- hosts: webservers
roles:
- role: debian_stock_config
when: ansible_facts['os_family'] == 'Debian'
根据事实选择变量、文件或模板
有时,主机的事实会决定您要为某些变量使用的值,甚至决定您要为该主机选择的文件或模板。例如,软件包的名称在 CentOS 和 Debian 上是不同的。常见服务的配置文件在不同的 OS 版本和版本上也是不同的。要根据主机的事实加载不同的变量文件、模板或其他文件,
将您的 vars 文件、模板或文件命名为与区分它们的 Ansible 事实匹配。
根据该 Ansible 事实使用基于变量的每个主机的正确 vars 文件、模板或文件。
Ansible 将变量与任务分开,使您的剧本不会变成带有嵌套条件语句的任意代码。这种方法会导致更简化且可审计的配置规则,因为要跟踪的决策点更少。
根据事实选择变量文件
您可以创建一个在多个平台和 OS 版本上运行的剧本,方法是将变量值放在 vars 文件中并有条件地导入它们。如果您想在一些 CentOS 和一些 Debian 服务器上安装 Apache,请创建带有 YAML 键和值的变量文件。例如:
---
# for vars/RedHat.yml
apache: httpd
somethingelse: 42
然后根据您在剧本中收集的主机的事实导入这些变量文件。
---
- hosts: webservers
remote_user: root
vars_files:
- "vars/common.yml"
- [ "vars/{{ ansible_facts['os_family'] }}.yml", "vars/os_defaults.yml" ]
tasks:
- name: Make sure apache is started
ansible.builtin.service:
name: '{{ apache }}'
state: started
Ansible 会在 webservers 组中的主机上收集事实,然后将变量“ansible_facts['os_family']”插入到文件名列表中。如果您有运行 Red Hat 操作系统(例如 CentOS)的主机,Ansible 会查找“vars/RedHat.yml”。如果该文件不存在,Ansible 会尝试加载“vars/os_defaults.yml”。对于 Debian 主机,Ansible 会首先查找“vars/Debian.yml”,然后再回退到“vars/os_defaults.yml”。如果列表中没有找到文件,Ansible 会引发错误。
根据事实选择文件和模板
当不同的 OS 版本或版本需要不同的配置文件或模板时,您可以使用相同的方法。根据分配给每个主机的变量选择适当的文件或模板。这种方法通常比将大量条件语句放入单个模板中以涵盖多个 OS 或软件包版本要干净得多。
例如,您可以将一个配置文件模板化,该配置文件在 CentOS 和 Debian 之间存在很大差异。
- name: Template a file
ansible.builtin.template:
src: "{{ item }}"
dest: /etc/myapp/foo.conf
loop: "{{ query('first_found', { 'files': myfiles, 'paths': mypaths}) }}"
vars:
myfiles:
- "{{ ansible_facts['distribution'] }}.conf"
- default.conf
mypaths: ['search_location_one/somedir/', '/opt/other_location/somedir/']
调试条件语句
如果您的条件语句 when
的行为与您的预期不符,您可以添加一个 debug
语句来确定条件是否评估为 true
或 false
。条件语句中出现意外行为的一个常见原因是将整数作为字符串或将字符串作为整数进行测试。要调试条件语句,请将整个语句作为 var:
值添加到 debug
任务中。然后,Ansible 会显示测试以及语句的评估方式。例如,这是一组任务和示例输出:
- name: check value of return code
ansible.builtin.debug:
var: bar_status.rc
- name: check test for rc value as string
ansible.builtin.debug:
var: bar_status.rc == "127"
- name: check test for rc value as integer
ansible.builtin.debug:
var: bar_status.rc == 127
TASK [check value of return code] *********************************************************************************
ok: [foo-1] => {
"bar_status.rc": "127"
}
TASK [check test for rc value as string] **************************************************************************
ok: [foo-1] => {
"bar_status.rc == \"127\"": false
}
TASK [check test for rc value as integer] *************************************************************************
ok: [foo-1] => {
"bar_status.rc == 127": true
}
常用事实
以下 Ansible 事实经常用于条件语句。
ansible_facts['distribution']
可能的值(示例,并非完整列表)
Alpine
Altlinux
Amazon
Archlinux
ClearLinux
Coreos
CentOS
Debian
Fedora
Gentoo
Mandriva
NA
OpenWrt
OracleLinux
RedHat
Slackware
SLES
SMGL
SUSE
Ubuntu
VMwareESX
ansible_facts['distribution_major_version']
操作系统的主要版本。例如,对于 Ubuntu 16.04,值为 16。
ansible_facts['os_family']
可能的值(示例,并非完整列表)
AIX
Alpine
Altlinux
Archlinux
Darwin
Debian
FreeBSD
Gentoo
HP-UX
Mandrake
RedHat
SMGL
Slackware
Solaris
Suse
Windows