我正在尝试构造一些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
我已经解决了,使用join和转义双引号。这是构造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