【问题标题】:Ansible Dictionary value not setAnsible 字典值未设置
【发布时间】:2021-04-02 17:22:59
【问题描述】:

我正在尝试用 ansible 填充字典中的值,但显然没有这样做。

我喜欢这样:

- name: Fill with zeros
  set_fact:
    item: "{{ item | combine(zero_fill, recursive=true) }}"
  vars:
    zero_fill: { 'json' : { 'data': { 'result': [{ 'value' : ["0.0","0.0"]}]}}}
  when: item.json.data.result == []
  with_items:
    - "{{ requests.results }}"

这个变量的一个项目是这样的:

{
...
"json": {
   "data": {
     "result": [],
     "resultType": "vector"
     }
   }
...
}

关键是在这个任务的输出中我确实看到了增加的价值,但是当我在任务之后立即打印它时,价值不存在。

【问题讨论】:

  • Ansible 的字典是不可变的。你必须创建一个新的。应该使用简单的结构。
  • 当您修改item 时,您不是在循环或原始数据中修改它,您只是在“全局”创建一个item 变量。您可以在循环后通过 - debug: var=item 看到这一点

标签: json loops dictionary ansible


【解决方案1】:

例如,新建一个列表results_zf,当json.data.result时用zero_fill更新字典json.data 是一个空列表

    - set_fact:
        results_zf: "{{ results_zf|default([]) + [_item] }}"
      loop: "{{ requests.results }}"
      vars:
        _item: "{{ (item.json.data.result|length > 0)|
                   ternary(item,
                           {'json': {'data': item.json.data|combine(zero_fill)}})
                           }}"

将字典zero_fill限制为属性result

    zero_fill:
      'result': [{'value': ["0.0","0.0"]}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-16
    • 2017-05-25
    • 2022-07-05
    • 2020-11-04
    • 2016-12-30
    • 1970-01-01
    • 2015-05-07
    • 2020-01-16
    相关资源
    最近更新 更多