2016-09-28 78 views
0

我正在编写Ansible play,其中一项任务是将条目附加到JSON文档。例如。使用jq附加从Ansible模板生成的输出

JSON文件staff.json

{ 
    "staff":[ 
     { 
     "john":[ 
      { 
       "position":"techwriter" 
      }, 
      { 
       "sex":"male" 
      } 
     ] 
     } 
    ] 
} 

我需要追加此项以staff

{ 
    "staff":[ 
     { 
     "john":[ 
      { 
       "position":"techwriter" 
      }, 
      { 
       "sex":"male" 
      } 
     ] 
     }, 
     { 
     "jane":[ 
      { 
       "position":"admin" 
      }, 
      { 
       "sex":"female" 
      } 
     ] 
     } 
    ] 
} 

条目将从Ansible template,像这样产生:

 { 
     "{{ staff_name }}":[ 
      { 
       "position":"{{ staff_position }}" 
      }, 
      { 
       "sex":"{{ staff_sex }}" 
      } 
     ] 
     } 

我学会了使用jqappend entry添加到JSON文档中,如“Add json array element with jq (cmdline)”中所示。但是,我不知道如何在Ansible中实现这一点,因为模板会输出到文件中。

我需要这样的东西的解决方案:

cat staff.json | jq '.staff |= .+ ["OUTPUT_FROM_TEMPLATE"]' 

任何想法表示欢迎。

+0

我删除了jq标签,因为您没有要求jq解决方案。 –

回答

1

您可以使用template查找插件:

- shell: cat staff.json | jq '.staff |= . + [{{ item | to_json }}]' > staff.json 
     with_template: person.j2 
     vars: 
     staff_name: jane 
     staff_position: admin 
     staff_sex: female 

请注意,您需要使用to_json滤波器item,因为Ansible模板引擎将JSON字符串,它可以评估到字典。

+0

工程就像一个魅力!我不知道'with_template'存在,很难从Ansible doc中挖掘出来。然而''staff.json'不适合我。我不得不使用'|发球区staff.json' –