首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >不可逆ansible.builtin.package变量替换

不可逆ansible.builtin.package变量替换
EN

Unix & Linux用户
提问于 2022-07-04 12:23:18
回答 1查看 87关注 0票数 1

遵循这里的示例;https://docs.ansible.com/ansible/latest/collections/ansible/builtin/package_module.html#examples

代码语言:javascript
运行
复制
# This uses a variable as this changes per distribution.
- name: Remove the apache package
  ansible.builtin.package:
    name: "{{ apache }}"
    state: absent

我看不出您将如何使该变量区分OS。如何根据发行版将该变量定义为apachehttpd

我知道如何在发行版的基础上发挥作用,但不像上面提到的那样用可变的替代;

代码语言:javascript
运行
复制
---
- 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"

我试图避免每次创建一个全新的任务,因为唯一的区别是要安装的包名,我创建的其他角色在操作系统类型之间是幂等的。

EN

回答 1

Unix & Linux用户

回答已采纳

发布于 2022-07-04 13:29:46

我看不出您将如何使该变量区分OS。如何根据发行版将该变量定义为apache或httpd?

有很多选择。

一个简单的解决方案是使用播放的vars_files部分,并让它根据操作系统名称加载一个变量文件。例如:

代码语言:javascript
运行
复制
- 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

代码语言:javascript
运行
复制
apache: httpd

或包含以下内容的文件vars/debian.yaml

代码语言:javascript
运行
复制
apache: apache2

如果需要更多的粒度,可以使用ansible_distribution而不是ansible_os_family (例如,ansible_os_family将是Fedora、CentOS、Red等下的Redhat,而ansible_distribution具有特定发行版的名称)。

如果您希望将此作为角色的一部分,则可以使用include_vars模块进行类似的操作。请参阅文档中的例句

代码语言:javascript
运行
复制
- 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'
票数 3
EN
页面原文内容由Unix & Linux提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://unix.stackexchange.com/questions/708567

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档