【问题标题】:Adding field to dict items将字段添加到 dict 项目
【发布时间】:2016-12-15 02:28:29
【问题描述】:

考虑下面的剧本。我想要做的是添加一个字段,tmp_path,它基本上是键和修订一起附加到脚本字典中的每个元素。

---
- hosts: localhost
  connection: local
  gather_facts: no
  vars:
    scripts:
      a.pl:
        revision: 123
      b.pl:
        revision: 456
  tasks:
     - with_dict: "{{ scripts }}"
       debug:
         msg: "{{ item.key }}_{{ item.value.revision }}"
#     - with_items: "{{ scripts }}"
#       set_fact: {{item.value.tmp_path}}="{{item.key}}_{{item.value.revision}}"
#     - with_items: "{{ scripts }}"
#       debug:
#         msg: "{{ item.value.tmp_path }}"
...

很明显,注释代码不起作用,知道我怎样才能让它工作吗?是否可以直接更改脚本字典,或者我应该以某种方式创建一个新的字典来引用?

顺便说一下,欢迎更正我正在尝试做的术语。

【问题讨论】:

    标签: ansible ansible-playbook


    【解决方案1】:

    好的,我想我找到了一个解决方案(如下),至少可以让我继续前进。缺点是它删除了我的 dict 的结构,并且似乎有点多余,必须重新定义所有字段并使用新变量,如果有人能提供更好的解决方案,我会接受。

    ---
    - hosts: localhost
      connection: local
      gather_facts: no
      vars:
        scripts:
          a.pl:
            revision: 123
          b.pl:
            revision: 456
      tasks:
         - with_dict: "{{ scripts }}"
           debug:
             msg: "{{ item.key }}_{{ item.value.revision }}"
         - with_dict: "{{ scripts }}"
           set_fact:
             new_scripts: "{{ (new_scripts | default([]))  + [ {'name': item.key, 'revision': item.value.revision, 'tmp_path': item.key ~ '_' ~ item.value.revision}] }}"
    #     - debug:
    #         var: x
    #     - with_dict: "{{ scripts }}"
         - with_items: "{{ new_scripts }}"
           debug:
             msg: "{{ item.tmp_path }}"
    ...
    

    顺便说一句,以下问题为我指明了正确的方向: Using Ansible set_fact to create a dictionary from register results

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 2019-10-23
      • 2019-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多