我需要将几个带有文件内容的词典添加到一个列表中,以便进一步与URI模块一起使用. 我现在正在手动操作,就像这样:

ansible.builtin.uri:
  method: POST
  body_format: json
  body:
    actions:
      - action: create
          file_path: ".gitlab-ci.yml"
          content: "{{ lookup('file', '.gitlab-ci.yml') }}"
      - action: create
          file_path: "README.md"
          content: "{{ lookup('file', 'README.md') }}"

我希望使此任务具有通用性,这样我就不必硬指定文件的名称:

ansible.builtin.set_fact:
  files:
   - .gitlab-ci.yml
   - README.md

ansible.builtin.uri:
  method: POST
  body_format: json
  body:
    actions: ["
      {% for fs in files -%}
      {
        'action': 'create',
        'file_path': '{{ fs }}',
        'content': '{{ lookup('file', fs) }}'
      }{% if not loop.last %},{% endif %}
      {%- endfor %}"
      ]

因此,文件的内容存储在Actions[*]Content变量中,但仅作为字符串存储,因为文件包含标记.如果将lookup替换为"Hello World"行,则会正常生成json. 你能告诉我如何使用looplookup来保存actions变量中有content键的文件的内容吗?

推荐答案

使用过滤器indent适当地缩进block.然后filter乘以from_yaml的 struct

    actions: |
      {% filter from_yaml %}
      {% for fs in files %}
      - action: create
        file_path: {{ fs }}
        content: |
          {{ lookup('file', fs)|indent(4) }}
      {% endfor %}
      {% endfilter %}

赠送

  actions:
  - action: create
    content: |-
      Content of .gitlab-ci.yml
      line 2
      line 3
      # EOF
    file_path: .gitlab-ci.yml
  - action: create
    content: |-
      Content of README.md
      line 2
      line 3
      # EOF
    file_path: README.md

您应该能够在uri模块中使用它

- ansible.builtin.uri:
    method: POST
    body_format: json
    body: "{'actions': {{ actions|to_json }} }"

(未测试)

Json相关问答推荐

中间初始化的Jolt配置

当有嵌套数组而没有嵌套数组时,展平JSON

我可以使用JQ来缩小数组中的json对象的范围吗?

错误:在 NX 工作区中找不到模块../swagger.json

(已回答)JSON 读取函数返回未定义而不是预期值 - Typescript

GitHub Pages无法正确显示我的项目

如何 Select 一个值,这是可选的 - 使用 jq

嵌套存储在字符串变量中的 JSON 对象

如何在linux中用jq过滤json数组?

现代浏览器一次可以处理多少个 HTML 元素?

Python Flask-Restful POST 不采用 JSON 参数

在 Apache Spark 中读取多行 JSON

如何从 mysql 数据库构建 JSON 数组

谷歌浏览器不允许我放置断点

了解 JSON Schema 草稿版本 4 中的additionalProperties关键字

如何访问 JSON 对象数组的第一个元素?

带有 Jackson 的不可变 Lombok 注释类

如何在dart Flutter 中将json字符串转换为json对象?

Newtonsoft 对象 → 获取 JSON 字符串

Backbone.js 模型与集合