Json post for API via Ansible

I want to make a POST request to an API endpoint via Ansible, where some elements inside the column data are dynamic, this is what I try and fail:

My body_content.json:

{ apiKey: '{{ KEY_FROM_VARS }}', data1: 'foo', data2: 'bar' } 

And here is my Ansible task:


 # Create an item via API - uri: url="http://www.myapi.com/create" method=POST return_content=yes HEADER_Content-Type="application/json" body="{{ lookup('file','create_body.json') | to_json }}" 

Unfortunately this does not work:

 failed: [localhost] => {"failed": true} msg: this module requires key=value arguments .... FATAL: all hosts have already failed -- aborting 

My available version is 1.9.1

+6
source share
2 answers

You cannot use newlines like this in yaml. Try this instead (">" means the following lines should be concatenated):

 # Create an item via API - uri: > url="http://www.myapi.com/create" method=POST return_content=yes HEADER_Content-Type="application/json" body="{{ lookup('file','create_body.json') | to_json }}" 

But I find it much better:

 # Create an item via API - uri: url: "http://www.myapi.com/create" method: POST return_content: yes HEADER_Content-Type: "application/json" body: "{{ lookup('file','create_body.json') | to_json }}" 
+10
source

I post below what I ended up using for my utility (Ansible 2.0). This is useful if your json payload is listed on a line (not a file).

this task expects 204 as a success return code.

And since body_format is json, the header is automatically output

 - name: add user to virtual host uri: url: http://0.0.0.0:15672/api/permissions/{{ rabbit_virtualhost }}/{{ rabbit_username }} method: PUT user: "{{ rabbit_username }}" password: "{{ rabbit_password }}" return_content: yes body: {"configure":".*","write":".*","read":".*"} body_format: json status_code: 204 

it is basically equivalent:

 curl -i -u user:pass -H "content-type:application/json" -XPUT http://0.0.0.0:15672/api/permissions/my_vhost/my_user -d '{"configure":".*","write":".*","read":".*"}' 
+1
source

Source: https://habr.com/ru/post/988097/


All Articles