指定 OS - Ansible

Specifying the OS - Ansible

我是 Ansible 的新手,所以我写了一个小的 ansible 实用程序来为我正在编写的系统安装一些包依赖项:

---

- hosts: all
  user: root
  tasks:
      - name: install requirements
        apt: name={{item}} state=latest update_cache=true
        with_items:
            - gcc
            - python-dev
            - python-setuptools
            - python-software-properties

当前支持的环境是UbuntuRed HatMac OS X。该剧本的当前编写方式仅适用于 Ubuntu (Debian)。我怎样才能让那部分代码根据 OS 执行? UbuntuaptRed HatyumMac OS X brew.

通常的做法是通过检查 ansible_os_family 事实有条件地包含一个 OS 家庭特定任务文件。

所以您的角色中可能有一个 main.yml 任务文件,类似于:

# Arbitrary task here, not needed but the point is you can have any generic tasks directly in main.yml
- name: get the date
  shell: `date`
  register: date

- include: debian.yml
  when: ansible_os_family == 'Debian'

- include: redhat.yml
  when: ansible_os_family == 'RedHat'

然后在 debian.yml 中我们有:

- name: install requirements
  apt: name={{item}} state=latest update_cache=true
  with_items:
      - gcc
      - python-dev
      - python-setuptools
      - python-software-properties

redhat.yml 中我们有:

- name: install requirements
  yum: name={{item}} state=latest update_cache=true
  with_items:
      - gcc
      - python-dev
      - python-setuptools
      - python-software-properties

显然,这也允许您根据 OS 系列设置不同的依赖项列表。

如果你愿意,你也可以有条件地包括 OS 系列(或任何你可以检查事实的东西)特定的变量,如下所示:

- name: Include OS-specific variables.
  include_vars: "{{ item }}"
  with_first_found:
    - ../vars/{{ ansible_distribution | lower }}.yml
    - ../vars/{{ ansible_os_family | lower }}.yml

然后像这样在 vars/debian.yml 中设置你的依赖列表:

python_dependencies:
  - gcc
  - python-dev
  - python-setuptools
  - python-software-properties

所以现在你的 tasks/debian.yml 看起来像:

- name: install requirements
  apt: name={{item}} state=latest update_cache=true
  with_items: python_dependencies

您可以通过查看源代码 here 查看 OS 及其家族的列表,其中包含所有 OS 家族的字典:

# A list with OS Family members
OS_FAMILY = dict(
    RedHat = 'RedHat', Fedora = 'RedHat', CentOS = 'RedHat', Scientific = 'RedHat',
    SLC = 'RedHat', Ascendos = 'RedHat', CloudLinux = 'RedHat', PSBM = 'RedHat',
    OracleLinux = 'RedHat', OVS = 'RedHat', OEL = 'RedHat', Amazon = 'RedHat',
    XenServer = 'RedHat', Ubuntu = 'Debian', Debian = 'Debian', Raspbian = 'Debian', Slackware = 'Slackware', SLES = 'Suse',
    SLED = 'Suse', openSUSE = 'Suse', SuSE = 'Suse', SLES_SAP = 'Suse', Gentoo = 'Gentoo', Funtoo = 'Gentoo',
    Archlinux = 'Archlinux', Manjaro = 'Archlinux', Mandriva = 'Mandrake', Mandrake = 'Mandrake',
    Solaris = 'Solaris', Nexenta = 'Solaris', OmniOS = 'Solaris', OpenIndiana = 'Solaris',
    SmartOS = 'Solaris', AIX = 'AIX', Alpine = 'Alpine', MacOSX = 'Darwin',
    FreeBSD = 'FreeBSD', HPUX = 'HP-UX'
)