Ansible支持在目标主机上执行特定任务之前进行条件评估。如果设定的条件为真,Ansible将继续执行该任务。如果条件不为真(未满足),Ansible将跳过指定的任务。
为了在Ansible中实现条件,我们使用when关键字。该关键字根据以前的任务或从远程主机收集到的事实的值或变量,接受布尔表达式。
本指南将教你如何使用when关键字在Ansible playbooks中实现条件。
Ansible的When条件:基本用法
when关键字的语法很简单。
when: (boolean condition)
确保传递一个条件,评估结果为真或假。
例如:
when: ansible_pkg_mgr == "yum"
when: ansible_user_shell" == "/bin/bash"
如果你想结合多个条件,你可以使用逻辑运算符,如and,or,和not。
when: (condition1) and (condition2)
when: (condition1) or (condition2)
为了理解如何使用Ansible的when关键字,我们将使用实际例子。
例1
第一个例子是,如果指定的用户在远程主机上不存在,将创建一个用户。
---
- hosts: all
gather_facts: no
become: true
tasks:
- name: checkifdirectoryexist
stat:
path: /home/ubuntu
register: dir
- name: createfileifdirectoryexists
file:
path: /home/ubuntu/file.txt
state: touch
when: dir.stat.exists
上面的例子首先检查ubuntu用户的主目录是否可用。然后,如果目录是可用的,我们使用when条件来创建一个文本文件。
例2
下一个例子使用when条件关闭了所有的Ubuntu远程主机。
---
- hosts: all
gather_facts: yes
become: true
tasks:
- name: shutdownUbuntuservers
command: /sbin/shutdown-tnow
when: ansible_facts['os_family']=="Ubuntu"
在上面的例子中,我们使用收集的事实来评估服务器是否来自Ubuntu家族。如果是,就关闭服务器。
例3
在下面的例子中,我们结合了两个使用and操作符的条件。
---
- hosts: all
gather_facts: yes
become: true
tasks:
- name: Installapacheserver
ansible.builtin.package:
name: httpd
state: latest
when: (ansible_facts['os_family']=="Debian")and
(ansible_facts['ansible_distribution_major_version']==10)
上面的例子检查主机是否为Debian主机,以及发行版本是否等于Debian 10。
例4
如果主机族是Debian或Ubuntu主机,我们在下面的playbook中安装Apache网络服务器。
该游戏手册使用了一个逻辑或操作符。
---
- hosts: all
gather_facts: yes
become: true
tasks:
- name: Installapacheserver
ansible.builtin.package:
name: httpd
state: latest
when: (ansible_facts['os_family']=="Debian")or
(ansible_facts['os_family']=="Ubuntu")
例5
考虑下面的操作手册,通过使用not操作符将Nginx服务器更新到最新版本。
---
- hosts: all
- shell: /sbin/nginx-v2>&1
register: version
gather_facts: yes
become: true
tasks:
- name: Installapacheserver
ansible.builtin.package:
name: nginx
state: latest
when: ('"nginx/1.19.0"notinversion.stdout')
如果Nginx服务器的输出不是当前版本,就安装当前版本的包。
总结
在本指南中,我们讨论了如何在Ansible中使用when关键字来处理条件反射。