遵循这里的示例;https://docs.ansible.com/ansible/latest/collections/ansible/builtin/package_module.html#examples
# This uses a variable as this changes per distribution.
- name: Remove the apache package
ansible.builtin.package:
name: "{{ apache }}"
state: absent
我看不出您将如何使该变量区分OS。如何根据发行版将该变量定义为apache
或httpd
?
我知道如何在发行版的基础上发挥作用,但不像上面提到的那样用可变的替代;
---
- name: Upgrade packages
hosts: all
become: true
tasks:
- name: Update all packages to the latest version Debian
ansible.builtin.apt:
update_cache: yes
cache_valid_time: 3600
upgrade: full
when: ansible_facts['os_family'] == "Debian"
- name: Update all packages to the latest version RedHat
ansible.builtin.dnf:
update_cache: yes
name: "*"
state: latest
when: ansible_facts['os_family'] == "RedHat"
我试图避免每次创建一个全新的任务,因为唯一的区别是要安装的包名,我创建的其他角色在操作系统类型之间是幂等的。
发布于 2022-07-04 13:29:46
我看不出您将如何使该变量区分OS。如何根据发行版将该变量定义为apache或httpd?
有很多选择。
一个简单的解决方案是使用播放的vars_files
部分,并让它根据操作系统名称加载一个变量文件。例如:
- hosts: all
gather_facts: true
vars_files:
- "vars/{{ ansible_os_family|lower }}.yaml"
tasks:
- name: Remove the apache package
ansible.builtin.package:
name: "{{ apache }}"
state: absent
这使用了ansible_os_family
的值,它由Ansible的事实收集支持提供。鉴于上述任务,您可能有一个包含以下内容的文件vars/redhat.yaml
:
apache: httpd
或包含以下内容的文件vars/debian.yaml
:
apache: apache2
如果需要更多的粒度,可以使用ansible_distribution
而不是ansible_os_family
(例如,ansible_os_family
将是Fedora、CentOS、Red等下的Redhat
,而ansible_distribution
具有特定发行版的名称)。
如果您希望将此作为角色的一部分,则可以使用include_vars
模块进行类似的操作。请参阅文档中的例句:
- name: Load a variable file based on the OS type, or a default if not found. Using free-form to specify the file.
ansible.builtin.include_vars: "{{ lookup('ansible.builtin.first_found', params) }}"
vars:
params:
files:
- '{{ansible_distribution}}.yaml'
- '{{ansible_os_family}}.yaml'
- default.yaml
paths:
- 'vars'
https://unix.stackexchange.com/questions/708567
复制相似问题