【问题标题】:Ansible run role based on condition基于条件的 Ansible 运行角色
【发布时间】:2021-01-16 16:20:47
【问题描述】:

我正在使用 Ansible 在 Linux 服务器上安装代理。根据系统是运行 systemd 还是 initd,有不同的安装过程。我为这两个安装过程都创建了一个角色,但我想先看看服务器是在运行 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'

【问题讨论】:

  • 你试过了吗?成功了吗?
  • 我有一个运行 systemd 的较新测试节点并且它可以工作,但不幸的是我没有运行 initd 的旧节点来查看条件是否真的有效。
  • 我确实在生产中运行的服务器上运行了特定命令,它们都返回值 1。
  • 您可能最好查看pidof 的返回码而不是输出(由于systemd 用户实例,您可以在多用户系统上获得pidof systemd 返回的多个pid) .或者,您可以检查/sbin/init;在启用 systemd 的系统上,该系统将成为 systemd 的符号链接。
  • "ansible_service_mgr": "systemd" 主机变量可能会让您感兴趣

标签: ansible roles


【解决方案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"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-09
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多