Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post Json to API via Ansible

I want to make a POST request to an API endpoint via Ansible where some of the items inside the post data are dynamic, here 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 }}"

Sadly this doesn't work:

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

My ansible version is 1.9.1

like image 213
Mudaer Avatar asked May 28 '15 14:05

Mudaer


2 Answers

I'm posting below what I ended up using for my usecase (Ansible 2.0). This is useful if your json payload is stated inline (and not in a file).

this task expects 204 as its success return code.

And since the body_format is json, the header is inferred automatically

- 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 to:

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":".*"}'
like image 109
FuzzyAmi Avatar answered Oct 10 '22 20:10

FuzzyAmi


You can't use newlines like this in yaml. Try this instead (the ">" indicates that the next lines are to 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 this 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 }}"
like image 24
Antonis Christofides Avatar answered Oct 10 '22 21:10

Antonis Christofides