【问题标题】:Ansible Task: with_dict statement got triggered, even if the when-clause should prevent thisAnsible Task: with_dict 语句被触发,即使 when 子句应该阻止这种情况
【发布时间】:2019-08-06 08:45:32
【问题描述】:

我正在尝试自动创建指向

的 smart_[diskdevice] 链接

/usr/share/munin/plugins/smart_

在通过 ansible 安装 munin 节点期间。

这里的代码部分工作,除了目标机器上没有要链接的磁盘设备。然后我遇到了致命的失败

{"msg": "with_dict expects a dict"}

我查看了 ansible 文档并尝试在网络中搜索问题。据我了解,如果“when”语句失败,则不应执行整个“file”指令。

---
- name: Install Munin Node
  any_errors_fatal: true
  block:
...

# drives config
    - file:
        src: /usr/share/munin/plugins/smart_
        dest: /etc/munin/plugins/smart_{{ item.key }}
        state: link
      with_dict: "{{ ansible_devices }}"
      when: "item.value.host.startswith('SATA')"
      notify:
        - restart munin-node

在带有 SATA 驱动器的目标上,该代码有效。找到像“sda”这样的驱动器并创建链接。循环和其他软设备被忽略(按预期) 只有在根本没有 SATA 驱动器的树莓上,我才遇到致命故障。

【问题讨论】:

  • ansible_devices 中有什么内容?在“文件”任务之前添加- debug: var=ansible_devices
  • 非常有趣:在我的 x86 目标上,我得到了设备的树形结构。但在 Raspi 上,我将所有设备集中在一条线上。缺少换行符。该系统是 4.15.0-1041-raspi2 #44-Ubuntu SMP PREEMPT aarch64 aarch64 aarch64 GNU/Linux
  • 如果您认为评论增加了价值,那么您可以提高它。然后其他人可以看到问题是否可能得到解决。

标签: ansible munin


【解决方案1】:

您正在使用with_dict 选项来设置loop。这会将每次迭代的 item 变量的值设置为具有两个键的字典:

  1. keydict中当前key的名称。
  2. valuedict中现有key的值。

然后您将运行when 选项,该选项在每次迭代中检查item 变量。因此,请检查这是否是您想要的行为。

关于您的错误,它被抛出是因为由于某种原因,ansible_devices 不是错误所说的dict。 Ansible 在解析when 条件之前检查with_dict 类型的有效性。

检查以下示例:

---
- name: Diff test
  hosts: local
  connection: local
  gather_facts: no
  vars:
    dict:
      value: True
      name: "dict"
  tasks:
    - debug: var=item
      when: dict.value == False
      with_dict: '{{ dict }}'

    - debug: var=item
      when: dict.value == True
      with_dict: '{{ dict }}'

    - debug: var=item
      when: dict.value == False
      with_dict: "Not a dict"

前两个task 将成功,因为它们在with_dict 选项上具有有效的dict,在when 选项上具有正确的条件。最后一个将失败,因为with_dict 值的类型错误,即使when 条件正确解析并且应该保证跳过task

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多