【问题标题】:ansible restrict role execution based on when conditionansible 根据 when 条件限制角色执行
【发布时间】:2021-04-12 12:17:36
【问题描述】:

我在为角色添加 when 条件时遇到了 ansible 语法错误。 我正在为此剧本使用动态库存。 下面是动态库存输出的例子:

{
  "_meta": {
    "hostvars": {
      "host1": {
        "Id": "1234567890",
        "enable_patching": "ENABLED"

      },
      "host2": {
        "Id": "123654290",
        "enable_patching": "DISABLED"
        }
}
}

下面是 ansible 剧本:

---
# This playbook will execute the inventory for applications account

- hosts: nonprod
  connection: local
  gather_facts: false
  serial: 1
  vars:
    tf_project: "nonprod"
  roles:
    - { role: patching, tags: [ 'patching' ], when:  "{{ hostvars[inventory_hostname]['enable_patching'] }}" = 'ENABLED'    }

我在运行 ansible playbook 时遇到错误

The offending line appears to be:


    - { role: patching, tags: [ 'patching' ], when:  "{{ hostvars[inventory_hostname]['enable_patching'] }}" = 'ENABLED'    }
                                                                                                             ^ here

如何在剧本中使用主机变量?不想在角色中使用 when 条件。

【问题讨论】:

  • 你的when中的=不应该是==吗?

标签: ansible


【解决方案1】:

这里发生了几件事。我认为如果您先修改语法,一些问题会变得更加明显:

- hosts: nonprod
  connection: local
  gather_facts: false
  vars:
    tf_project: "nonprod"
  roles:
    - role: patching
      tags: [ 'patching' ]
      when:  "{{ hostvars[inventory_hostname]['enable_patching'] }}" = 'ENABLED'    }

这里的直接问题是,如果你用引号开始一个值, 那么 entire 值必须在引用的字符串内。那是, 你不能写:

when: "some value" followed by something else

你只能写:

when: "some value followed by something else"

无需处理烦人的引号转义即可解决此问题的一种简单方法是使用 YAML 的引号运算符之一,例如 >

when:  >-
  hostvars[inventory_hostname]['enable_patching'] == 'ENABLED'

您的第二个问题是 when 条件不接受 jinja 模板标记 ({{...}})。

最后,您使用== 来比较相等性,而不是=

- hosts: nonprod
  connection: local
  gather_facts: false
  vars:
    tf_project: "nonprod"
  roles:
    - role: patching
      tags: [ 'patching' ]
      when:  >-
        hostvars[inventory_hostname]['enable_patching'] == 'ENABLED'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-28
    • 1970-01-01
    • 2021-01-16
    • 2022-01-25
    • 2021-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多