ansible 不同 Linux 发行版的相同剧本

sou*_*ung 6 ubuntu module centos ansible

我们为安装了 Ubuntu 的节点设计了一个 ansible playbook。

现在我们必须在新机器(节点)上为使用 Centos 的不同客户播放相同的 Playbook。

问题在于,对于 Centos,Ansible 使用 Yum 模块(使用 yum 包管理器来安装模块)。在我们的实际剧本中,我们显然正在使用 apt 模块。

Ansible 建议采取什么措施来更好地管理这种情况?

  • 为 Centos 重写一个版本的剧本是否更好?
  • 或者保留相同的剧本并在 Ubuntu 上动态使用“apt”是否更好?或者 Centos 上的百胜?
  • 还有其他更合适的解决方案吗?

miw*_*iwa 7

一种常见的方法是为多个发行版编写一个剧本,其中包含多个条件,或者只是将特定于发行版的任务分离到不同的文件中,并将这些文件包含到主要角色中,如下所示

# Perform distro-specific tasks.
- include_tasks: setup-"{{ ansible_distribution }}".yml
Run Code Online (Sandbox Code Playgroud)

因此setup-Ubuntu.yml,在 filessetup-CentOS.yml等中,您将保留特定于特定 Linux 的所有操作。另请参阅 Geerlingguy 的角色作为一个合适的例子。

如果您只想安装或删除软件包而不使用 apt 或 yum 中更复杂的功能,您可以使用相当简单的软件包模块,但如果这对您来说足够了,那么您将获得针对不同 Linux 风格的相同代码。

另外,您需要考虑到在 Ubuntu 和 CentOS 中,许多文件(包括配置文件和程序二进制文件)位于不同的位置。因此,如果您决定使用包模块,您可以通过使用外部文件以如下方式处理特定于发行版的事情:

- name: Load a variable file based on the OS type, or a default if not found.
  include_vars: "{{ item }}"
  with_first_found:
    - "{{ ansible_distribution }}-vars.yaml"
    - "{{ ansible_os_family }}-vars.yaml"
    - default-vars.yaml
Run Code Online (Sandbox Code Playgroud)

完成此任务后,您可以使用上述文件中定义的变量,并使用特定于您的平台的值进行初始化,如下所示

- name: Apply some config template
  template:
    src: my_config_template.j2
    dest: "{{ distro_specific_destination }}"
    validate: "{{ distro_specific_command }} %s"
Run Code Online (Sandbox Code Playgroud)