Ansible 运行 角色基于条件

Ansible run role based on condition

我正在使用 Ansible 在 Linux 服务器上安装代理。根据系统是 运行ning systemd 还是 initd,有不同的安装过程。我为两个安装过程都创建了一个角色,但我想先看看服务器是 运行ning systemd 还是 initd,然后 运行 相应的角色。下面是我创建的代码。这种类型的条件会以这种方式起作用还是我错过了标记?

  tasks:
    - name: check if running initd or systemd and role the correct role
      command: pidof systemd
      register: pid_systemd

    - name: check if running initd or systemd and role the correct role
      command: pidof /sbin/init
      register: pid_initd

    - include_role:
        name: install-appd-machine-agent-initd
      when: pid_initd.stdout == '1'

    - include_role:
        name: install-appd-machine-agent-systemd
      when: pid_systemd.stdout == '1'

Ansible 通过 setup 模块使用 gather_facts 收集系统的事实。这提供了一个名为 ansible_service_mgr 的魔法变量。此变量可用于有条件地执行任务。

例如,有条件地运行您的角色:

  tasks:
  - include_role:
      name: install-appd-machine-agent-initd
    when: ansible_service_mgr == "sysvinit"
  - include_role:
      name: install-appd-machine-agent-systemd
    when: ansible_service_mgr == "systemd"