我有一个 Ansible 剧本(使用 ansible 1.9.3),可以设置和更新一堆服务器。这些步骤之一是安装软件包(使用“apt”插件)。直到最近我的所有服务器都是统一的(相同版本的 Ubuntu 服务器)。我正在引入一个较新的 Ubuntu 服务器,并且一些软件包名称已更改。
这是我的任务文件的样子:
- name: install needed packages
apt: name={{ packages }} state=present update_cache=yes
(我在 vars 文件中有一个包列表)。
我可以在清单文件中为具有不同 Ubuntu 版本的主机定义一个变量。
如何更改此任务以对当前主机使用一个软件包列表,对新主机使用另一个软件包列表?
使用
when
子句。这是一个仅在 ubuntu 12.04 上运行的示例
when: "'{{ ansible_distribution}}' == 'Ubuntu' and '{{ ansible_distribution_release }}' == 'precise'"
您也可以使用:
when: "'{{ ansible_distribution }}' == 'Ubuntu' and '{{ ansible_distribution_version }}': '12.04'"
编辑: Ansible 的更高版本(例如 2.7.1)会为此语句打印警告:
[警告]:when 语句不应包含 jinja2 模板分隔符,例如 {{ }} 或 {% %}。找到:'{{ansible_distribution}}' == 'Ubuntu' 和 '{{ ansible_distribution_release }}' == 'bionic'
Ansible 现在需要条件语句的另一种语法,如文档中所述。
对于 Ansible 2.5 你可以尝试这个:
when: "ansible_distribution|string == 'Ubuntu' and ansible_distribution_release|string == 'bionic'"
甚至:
when:
- ansible_distribution|string == 'Ubuntu'
- ansible_distribution_release|string == 'bionic'
最新版本的文档建议使用这样的方式访问ansible_facts:
when:
- ansible_facts['distribution'] == "CentOS"
- ansible_facts['distribution_major_version'] == "6"
tasks/main.yml
,它将包含与
when
使用的条件匹配的任务,例如,如果使用
ansible_os_family
main.yml
的内容可能类似于:
---
- include_tasks: freebsd.yml
when: ansible_os_family == "FreeBSD"
tags:
- unbound
- include_tasks: debian.yml
when: ansible_os_family == "Debian"
tags:
- unbound
- include_tasks: redhat.yml
when: ansible_os_family == "RedHat"
tags:
- unbound
这种方法的优点是,除了每个操作系统只有一组任务之外,您还可以标记完整的任务。
只需将每个发行版的包存储在字典中
变量文件:
packages: {
bionic: [ bionic-package1, bionic-package2],
focal: [focal-package1, focal-package2]
}
剧本:
- name: Install unique packages per distro
package:
name: "{{ packages[ansible_distribution_release] }}"
state: present
请注意,从“apt”到“package”模块的更改允许任务在任何 Linux 发行版上运行,而不仅仅是使用 apt 作为包管理器的发行版