Reputation: 143
All
I am using Ansible to POST data on a website. I have taken a very simple example of the JSON content
{
"test2":"{{test}}"
}
Below is snippet for ansible task responsible to POST data:
vars:
test: "somerandomtest"
tasks:
- name: Test
register: json_output
uri:
url: "http://localhost:3000"
validate_certs: no
follow_redirects: none
headers:
Authorization: Bearer 12344
Content-Type: application/json
method: POST
body_format: json
body: " {{ lookup('file','test.json') | from_json }} "
#body: '{"test2":" {{test}} "}'
timeout: 600
But on the web service I see the below data, where "test" is not replaced with "somerandomtest".
{'test2': '{{test}}'}
Not sure what I am doing wrong, or maybe I am using lookup the wrong way. If I replace the body with the content everything is fine, but the real JSON I work with is 400 lines, and I want to keep it separate.
Can anyone please let me know what can I do to change the JSON data using Ansible?
Upvotes: 0
Views: 1119
Reputation: 67959
Put the hash into a dictionary and format it to_json. For example
- hosts: localhost
vars:
test: somerandomtest
body:
test2: "{{ test }}"
tasks:
- debug:
msg: "{{ body|to_json }}"
gives the JSON
msg: '{"test2": "somerandomtest"}'
The template gives the same result
shell> cat test.json
{
"test2": "{{ test }}"
}
- debug:
msg: "{{ lookup('template','test.json')|to_json }}"
Upvotes: 1
Reputation: 311238
The file
lookup doesn't evaluate file content for Jinja template markers (which would lead to unexpected behavior if a document just happened to contain {{
).
If you want to read in a template, use the template
lookup instead:
- hosts: localhost
gather_facts: false
tasks:
vars:
test: "somerandomtest"
tasks:
- name: Test
register: json_output
uri:
url: "https://httpbin.org/post"
validate_certs: no
follow_redirects: none
headers:
Content-Type: application/json
method: POST
body_format: json
body: " {{ lookup('template','test.json') }} "
return_content: true
timeout: 600
- debug:
var: json_output
This shows that the content sent to the remote server is:
{'test2': 'somerandomtest'}
Upvotes: 1