Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix body_json parsing of api_request module #342

Merged
merged 4 commits into from
Apr 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion plugins/modules/api_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@

from __future__ import absolute_import, division, print_function

import ast
import contextlib

# pylint: disable=unused-import
import json
from typing import Any, Optional, Tuple
Expand Down Expand Up @@ -99,6 +102,15 @@ def __init__(self) -> None:
mutually_exclusive=[("body", "body_json")],
)

@staticmethod
def _parse_body_json(body_content: str) -> dict:
with contextlib.suppress(Exception):
# If this is a Python dict literal, parse and return
result = ast.literal_eval(body_content)
return result

return json.loads(body_content)

def do_request(
self, method: str, path: str, filters: dict = None, body: dict = None
) -> Tuple[int, Optional[dict]]:
Expand Down Expand Up @@ -138,7 +150,7 @@ def exec_module(self, **kwargs: Any) -> Optional[dict]:
if param_body is not None:
request_body = param_body
elif param_body_json is not None:
request_body = json.loads(param_body_json)
request_body = self._parse_body_json(param_body_json)

response_status, response_json = self.do_request(
param_method, param_path, filters=param_filter, body=request_body
Expand Down
48 changes: 48 additions & 0 deletions tests/integration/targets/api_request_extra/tasks/main.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# this test is to test a json_body with integer inside as a value of a key

- name: api_request_extra
block:
- set_fact:
r: "{{ 1000000000 | random }}"

- name: List all available Linode regions
linode.cloud.region_list:
register: regions

- name: Create a volume by the api_request module
linode.cloud.api_request:
path: "/volumes"
method: POST
body_json: >
{
"label": "ansible-test-{{ r }}",
"size": 10,
"region": "{{ regions.regions[0].id }}"
}
register: response

- name: Assert volume created
assert:
that:
- response.changed

always:
- ignore_errors: true
block:
- name: Delete the volume
linode.cloud.volume:
label: '{{ response.body.label }}'
state: absent
register: delete_volume
until: delete_volume.changed
retries: 5
delay: 10

- name: Assert the volume was deleted
assert:
that:
- delete_volume.changed

environment:
LINODE_UA_PREFIX: '{{ ua_prefix }}'
LINODE_API_TOKEN: '{{ api_token }}'