2016-12-15 142 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