首页 > 解决方案 > 如何从列表 var 构建 json 字符串

问题描述

我正在尝试构建一些 JSON 以在 Ansible uri POST 任务中使用。我有一个“标签”列表:

ok: [testserver] => {
    "post_tags": [
        "st_unclass_app", 
        "st_test_app"
    ]
}

而且我需要为 uri 任务的 POST 方法的主体创建一个 JSON 字符串。标签列表构成了完整字符串的一部分,因此我需要构造一个事实,即整个 JSON 代码部分的字符串。字符串应该如下所示:

{"tag": "st_unclass_app"}, {"tag": "st_test_app"}

我的问题有两个:1)标签的数量会有所不同,所以我需要使这个长度动态化。和 2) 字符串是用 JSON 相关字符构造的,我知道我必须导航它。

到目前为止,我无法在任何地方找到任何有用的提示,但仍在寻找。搜索“将字符串连接到列表”等内容不会返回任何有用的信息。

这是我需要完成的静态任务

  - name: Apply tags
      uri:
        url: https://{{ nsxt_host }}/api/v1/fabric/virtual-machines?action=update_tags
        method: POST
        user: "{{ nsxt_user }}"
        password: "{{ nsxt_pass }}"
        force_basic_auth: yes
        validate_certs: no
        headers:
          Content-Type: application/json
          Accept: :application/json,version=2
        body: {"external_id": '{{ nsxt_record.json.results[0].external_id }}', "tags": [{"tag": "st_unclass_app"}, {"tag": "st_test_app"}]}
        body_format: json
      delegate_to: localhost

我期待它看起来像这样:

  - name: Apply tags
      uri:
        url: https://{{ nsxt_host }}/api/v1/fabric/virtual-machines?action=update_tags
        method: POST
        user: "{{ nsxt_user }}"
        password: "{{ nsxt_pass }}"
        force_basic_auth: yes
        validate_certs: no
        headers:
          Content-Type: application/json
          Accept: :application/json,version=2
        body: {"external_id": '{{ nsxt_record.json.results[0].external_id }}', "tags": ['{{ nsxt_tags }}']}
        body_format: json
      delegate_to: localhost

标签: jsonansible

解决方案


我已经解决了,使用连接和转义双引号。下面是构造 JSON 的任务:

- name: Build tag string
      set_fact:
        nsxt_tags: "{\"tag\": \" {{ post_tags | join('\"}, {\"tag\": \"') }} \"}"

这是更新 uri 任务:

- name: Apply tags
      uri:
        url: https://{{ nsxt_host }}/api/v1/fabric/virtual-machines?action=update_tags
        method: POST
        user: "{{ nsxt_user }}"
        password: "{{ nsxt_pass }}"
        force_basic_auth: yes
        validate_certs: no
        headers:
          Content-Type: application/json
          Accept: :application/json,version=2
        body: {"external_id": '{{ nsxt_record.json.results[0].external_id }}', "tags": '{{ nsxt_tags }}'}
        body_format: json
      delegate_to: localhost

推荐阅读