【问题标题】:Using jq to append output generated from Ansible template使用 jq 附加从 Ansible 模板生成的输出
【发布时间】:2016-09-29 13:49:18
【问题描述】:

我正在编写 Ansible 游戏,其中一项任务是将条目附加到 JSON 文档。例如

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

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

我需要这样的解决方案:

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

欢迎任何想法。

【问题讨论】:

  • 我正在删除 jq 标签,因为您不要求 jq 解决方案。

标签: json ansible


【解决方案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 字符串转换为dict。

【讨论】:

  • 像魅力一样工作!我不知道with_template 存在,也很难从 Ansible 文档中挖掘出来。但是,> staff.json 对我不起作用。我不得不使用| tee staff.json
猜你喜欢
  • 2018-03-04
  • 1970-01-01
  • 2011-06-12
  • 2020-07-11
  • 1970-01-01
  • 1970-01-01
  • 2021-09-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多