2016-12-15 147 views
1

请考虑以下玩法。我想要做的是添加一个字段,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 }}" 
... 

很明显,评论的代码不起作用,任何想法我怎么能得到这个工作?是否可以直接更改脚本词典,或者我应该创建一个新的词典来引用?

顺便说一句,欢迎纠正我尝试做的术语。

回答

0

好吧,我想我有一个解决方案(下图),至少让我向前迈进。缺点是它已经删除了我的字典的结构,并且似乎有点多余,不得不重新定义所有字段并使用新的变量,如果任何人都可以提供更好的解决方案,我会接受。

--- 
- 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 }}" 
... 

BTW贷到以下问题该向我指出了正确的方向: Using Ansible set_fact to create a dictionary from register results