Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple status_code in Ansible uri module

Tags:

uri

ansible

I am using ansible uri module to make a POST request. The request returns status either 201 or 208 and both status code should be considered for the task to pass. How can I specify multiple status_code value or how can I achieve this?

  - uri:
      url: "http://mywebsite.org/api/hooks/release/builtin/"
      method: POST
      HEADER_Content-Type: "application/json"
      body: '{"version": "6.2.10"}'
      body_format: json
      status_code: 208
    register: result
    failed_when: status_code != 201 or status_code != 208
like image 944
drishti ahuja Avatar asked Jan 05 '17 10:01

drishti ahuja


3 Answers

Per uri module manual:

status_code A valid, numeric, HTTP status code that signifies success of the request. Can also be comma separated list of status codes.

So:

- uri:
    url: "http://mywebsite.org/api/hooks/release/builtin/"
    method: POST
    HEADER_Content-Type: "application/json"
    body: '{"version": "6.2.10"}'
    body_format: json
    status_code: 201, 208
  register: result
like image 149
techraf Avatar answered Nov 15 '22 22:11

techraf


It is worth noting that you can also give the status codes in a more traditional ansible list format (one item per line):

- uri:
  url: "http://mywebsite.org/api/hooks/release/builtin/"
  method: POST
  HEADER_Content-Type: "application/json"
  body: '{"version": "6.2.10"}'
  body_format: json
  status_code:
    - 201
    - 208
    - 409
register: result
like image 33
Rand Avatar answered Nov 15 '22 23:11

Rand


The solution using failed_when

The failed_when needs to use not in and result.status to evaluate this correctly like this:

failed_when: result.status not in [201,208]

Problem with the code in the question The first issue is that status_code cannot be referenced like this. However, you can reference status using the registered result object. So then the failed_when statemment would look like: failed_when: result.status != 201 or result.status != 208

However, this still fails when 201 or 208 are returned since if the status is 208 then it does not equal 201 and the result.status != 201 conditional fails (and vice versa).

like image 1
ddrake12 Avatar answered Nov 16 '22 00:11

ddrake12