Ansible: access json field and use it as variable -
i have send put requests server, @ url: https://xxxx.com/id, , passing body json files (item1.json, item2.json ...).
- name: invoke service uri: url: "https://xxxx.com/{{ item.id }}" method: put return_content: yes body_format: json headers: content-type: "application/json" x-auth-token: "xxxxxx" body: "{{ lookup('file', item) }}" with_items: - item1.json - item2.json - item3.json
the id parameter of url within respective json file. structure of json files following:
{ "address": "163.111.111.111", "id": "ajsaljlsaaj", "server": "dnnwqkwnlqkwnldkwqldn" }
the code have written seems not work, , 'ansible.vars.unsafe_proxy.ansibleunsafetext object' has no attribute 'id'. how can field been accessed?
the issue in following line:
url: "https://xxxx.com/{{ item.id }}"
the value of item
json file name defined in with_items
, not content of json file.
the quickest fix open , parse json file same way in body:
declaration:
- name: invoke service uri: url: "https://xxxx.com/{{ ( lookup('file', item)|from_json ).id }}" method: put return_content: yes body_format: json headers: content-type: "application/json" x-auth-token: "xxxxxx" body: "{{ lookup('file', item) }}" with_items: - item1.json - item2.json - item3.json
one nicer solution use with_file:
directive instead of with_items
.
with_file
automatically open , read file content, no need call lookup
anymore:
- name: provision docker swarm managers hosts: localhost tags: provision gather_facts: false become: true tasks: - name: invoke service uri: url: "https://xxxx.com/{{ (item|from_json).id }}" method: put return_content: yes body_format: json headers: content-type: "application/json" x-auth-token: "xxxxxx" body: "{{ item }}" with_file: - item1.json - item2.json - item3.json
Comments
Post a Comment