使用 ansible 包模块来处理 apt 和 homebrew

use*_*462 2 macos homebrew ansible

我在创建适用于 linux 和 macOS 的剧本时遇到两个问题。

我的剧本中有很多这样的步骤:

- name: install something
  package:
    name: [something_1, something_2, ...]
    state: present
  become: yes
Run Code Online (Sandbox Code Playgroud)

它适用于 apt 和 yum,但是当我尝试在 macOS 上运行它时,自制软件会抱怨:

Running Homebrew as root is extremely dangerous and no longer supported.

我在很多地方都找不到解决这个问题的优雅方法。复制所有任务并使用when子句对我来说似乎势不可挡。可能我可以根据分布将 become_user 变量设置为 root/local_user,但这也有很多变化。

第二个问题是 head-only 公式(只能使用 --head 标志安装的自制软件包)。如果 something_2 需要安装这个标志怎么办?同样,我可以复制任务并将模块更改为自制软件,但这是很多样板。

有什么帮助吗?

sh7*_*h78 7

如果你想要一组足够灵活的任务来处理多个 Linux 包管理器和 macOS brew,那么选择要么是更多的逻辑,要么是更多的重复。

这三种模式应该会有所帮助。他们仍然有重复和样板代码,但这就是我们使用 Ansible 跨平台播放的领域。

  1. become: yes仅针对 Linux 全局声明(root)
  2. 根据需要处理需要特定于平台的处理的地址包 when
    • 这可能是--headbrew,或为apt等设置 PPA
  3. 映射包名称与变量的差异
    • 例如:brew install ncursesapt install libncurses5-devdnf install ncurses-devel都是同一个库。

1)become: yes仅针对 Linux 全局声明(root)

对于 Linux 主机,切换到 root 进行安装是预期行为。对于 macOS a la Homebrew,以 root 身份安装并不好。因此,我们需要become: nofalse使用时)brew,和become: yestrue)否则(对于Linux)。

在您的示例中,become指令嵌套在每个任务(“步骤”)中。为防止重复,请become在任务开始之前在更高的词法范围内调用。随后的任务将继承 的状态become,该状态是基于条件表达式设置的。

不幸的是become,根剧本范围的变量将是未定义的,并在运行第一个任务之前抛出错误:

# playbook.yml
- name: Demo
  hosts: localhost
  connection: local
  # This works
  become: True
  # This doesn't - the variable is undefined
  become: "{{ False if ansible_pkg_mgr == 'brew' else True }}"
  # Nor does this - also undefined
  become: "{{ False if ansible_os_family == 'Darwin' else True }}"

  tasks:
    # ...
Run Code Online (Sandbox Code Playgroud)

为了解决这个问题,我们可以将任务存储在另一个文件中并导入它们,或者将任务包装在一个块中。这些模式中的任何一个都将提供机会及时声明become我们的自定义变量值,以便任务选择它:

# playbook.yml
---
- name: Demo
  hosts: localhost
  connection: local
  vars:
    # This variable gives us a boolean for deciding whether or not to become
    # root. It cascades down to any subsequent tasks unless overwritten.
    should_be_root:  "{{ true if ansible_pkg_mgr != 'brew' else false }}"

    # It could also be based on the OS type, but since brew is the main cause
    # it's probably better this way.
    # should_be_root: "{{ False if ansible_os_family == 'Darwin' else True }}"

  tasks:
    # Import the tasks from another file, which gives us a chance to pass along
    # a `become` context with our variable:
    - import_tasks: test_tasks.yml
      become: "{{ should_be_root }}"

    # Wrapping the tasks in a block will also work:
    - block:
      - name: ncurses is present
        package:
          name: [libncurses5-dev, libncursesw5-dev]
          state: present
      - name: cmatrix is present
        package:
          name: cmatrix
          state: present
      become: "{{ should_be_root }}"
Run Code Online (Sandbox Code Playgroud)

现在有一个单一的逻辑检查brew和一个单一的before指令(取决于上面使用的任务模式)。所有任务都将以 root 用户身份执行,除非使用的包管理器是brew.

2)根据需要处理需要特定平台处理的包 when

封装模块是一个极大的方便,但它是相当有限的。它本身只适用于理想的场景;意思是,一个不需要任何特殊处理或来自底层包管理器的标志的包。它所能做的就是传递要安装的包的文字字符串state、 和一个可选参数来强制使用特定的包管理器可执行文件。

这是一个示例,它安装wget了一个很好的简短任务,并且只有ffmpeg在安装时才会变得冗长以处理的特殊情况brew

# playbook.yml
# ...
  tasks:
    # wget is the same among package managers, nothing to see here
    - name: wget is present
      when: ansible_pkg_mgr != 'brew'
      package:
        name: wget
        state: present

    # This will only run on hosts that do not use `brew`, like linux
    - name: ffmpeg is present
      when: ansible_pkg_mgr != 'brew'
      package:
        name: ffmpeg
        state: present

    # This will only run on hosts that use `brew`, i.e. macOS
    - name: ffmpeg is present (brew)
      when: ansible_pkg_mgr == 'brew'
      homebrew:
        name: ffmpeg
        # head flag
        state: head
        # --with-chromaprint --with-fdk-aac --with-etc-etc
        install_options: with-chromaprint, with-fdk-aac, with-etc-etc
Run Code Online (Sandbox Code Playgroud)

上面的游戏将ffmpeg针对 Linux 机器生成以下输出:

TASK [youtube-dl : ffmpeg is present] ******************************************
ok: [localhost]

TASK [youtube-dl : ffmpeg is present (brew)] ***********************************
skipping: [localhost]
Run Code Online (Sandbox Code Playgroud)

3) 映射包名与变量的差异

这不是您问题的具体部分,但接下来可能会出现。

封装模块的文档也提到:

包名称也因包管理器而异;该模块不会在每个发行版中“翻译”它们。例如 libyaml-dev、libyaml-devel。

因此,我们自行处理相同软件在包管理器平台之间使用不同名称的情况。这是很常见的。

这有多种模式,例如:

他们都不是很愉快。这是一种使用角色的方法。角色确实涉及更多样板和目录杂耍,但作为交换,它们提供了模块化和局部变量环境。当一个角色中的一组任务需要更多的努力才能正确时,它最终不会污染其他任务集。

TASK [youtube-dl : ffmpeg is present] ******************************************
ok: [localhost]

TASK [youtube-dl : ffmpeg is present (brew)] ***********************************
skipping: [localhost]
Run Code Online (Sandbox Code Playgroud)

任务 forncurses查找由相应包管理器键控的要循环的项目数组。如果正在使用的包管理器未在变量对象中定义,则使用 Jinja 默认过滤器来引用default我们设置的 值。

使用此模式,添加对另一个包管理器或附加依赖项的支持只需更新变量对象:

# playbook.yml
---
- name: Demo
  hosts: localhost
  connection: local
  roles:
    - cmatrix

# roles/cmatrix/defaults/main.yml
---
ncurses:
  default:
    - ncurses
  # Important: these keys need to exactly match the name of package managers for
  # our logic to hold up
  apt:
    - libncurses5-dev
    - libncursesw5-dev
  brew:
    - pkg-config
    - ncurses

# roles/cmatrix/tasks/main.yml
---
- name: cmatix and its dependencies are present
  become: "{{ should_be_root }}"
  block:
    - name: ncurses is present
      package:
        name: '{{ item }}'
        state: latest
      loop: "{{ ncurses[ansible_pkg_mgr] | default(ncurses['default']) }}"

    - name: cmatrix is present
      when: ansible_pkg_mgr != 'brew'
      package:
        name: cmatrix
        state: present
Run Code Online (Sandbox Code Playgroud)

将一切结合成一场真正的戏剧

这是一个涵盖所有三个方面的完整示例。该剧本有两个角色,每个角色都使用become基于单个变量的正确值。它还包含一个特殊情况cmatrixffmpeg当安装时使用 brew, 并处理包管理器之间 ncurses 的备用名称。

# roles/cmatrix/defaults/main.yml
---
ncurses:
  default:
    - ncurses
  apt:
    - libncurses5-dev
    - libncursesw5-dev
    # add a new dependency for Debian
    - imaginarycurses-dep
  brew:
    - pkg-config
    - ncurses
  # add support for Fedora
  dnf:
    - ncurses-devel
Run Code Online (Sandbox Code Playgroud)
# playbook.yml
---
- name: Demo
  hosts: localhost
  connection: local
  vars:
    should_be_root:  "{{ true if ansible_pkg_mgr != 'brew' else false }}"
  roles:
    - cmatrix
    - youtube-dl
Run Code Online (Sandbox Code Playgroud)
# roles/cmatrix/defaults/main.yml
ncurses:
  default:
    - ncurses
  apt:
    - libncurses5-dev
    - libncursesw5-dev
  brew:
    - pkg-config
    - ncurses
  dnf:
    - ncurses-devel

Run Code Online (Sandbox Code Playgroud)
# roles/cmatrix/tasks/main.yml
---
- name: cmatrix and dependencies are present
  # A var from above, in the playbook
  become: "{{ should_be_root }}"

  block:
    - name: ncurses is present
      package:
        name: '{{ item }}'
        state: latest
      # Get an array of the correct package names to install from the map in our
      # default variables file
      loop: "{{ ncurses[ansible_pkg_mgr] | default(ncurses['default']) }}"

    # Install as usual if this is not a brew system
    - name: cmatrix is present
      when: ansible_pkg_mgr != 'brew'
      package:
        name: cmatrix
        state: present
    # If it is a brew system, use this instead
    - name: cmatrix is present (brew)
      when: ansible_pkg_mgr == 'brew'
      homebrew:
        name: cmatrix
        state: head
        install_options: with-some-option
Run Code Online (Sandbox Code Playgroud)

Ubuntu 的结果:

$ ansible-playbook demo.yml
[WARNING]: provided hosts list is empty, only localhost is available. Note that
the implicit localhost does not match 'all'

PLAY [Demo] ********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [localhost]

TASK [cmatrix : ncurses is present] ********************************************
ok: [localhost] => (item=libncurses5-dev)
ok: [localhost] => (item=libncursesw5-dev)

TASK [cmatrix : cmatrix is present] ********************************************
ok: [localhost]

TASK [cmatrix : cmatrix is present (brew)] *************************************
skipping: [localhost]

TASK [youtube-dl : ffmpeg is present] ******************************************
ok: [localhost]

TASK [youtube-dl : ffmpeg is present (brew)] ***********************************
skipping: [localhost]

TASK [youtube-dl : atomicparsley is present] ***********************************
ok: [localhost]

TASK [youtube-dl : youtube-dl is present] **************************************
ok: [localhost]

PLAY RECAP *********************************************************************
localhost                  : ok=6    changed=0    unreachable=0    failed=0    skipped=2    rescued=0    ignored=0
Run Code Online (Sandbox Code Playgroud)