| 1 |
# Copyright (c) Ansible project |
| 2 |
# Simplified BSD License (see LICENSES/BSD-2-Clause.txt or https://opensource.org/licenses/BSD-2-Clause) |
| 3 |
# SPDX-License-Identifier: BSD-2-Clause |
| 4 |
|
| 5 |
# Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time. |
| 6 |
# Do not use this from other collections or standalone plugins/modules! |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
import json |
| 11 |
import sys |
| 12 |
import typing as t |
| 13 |
from http import HTTPStatus |
| 14 |
|
| 15 |
from ansible.module_utils.basic import env_fallback |
| 16 |
from ansible.module_utils.urls import fetch_url |
| 17 |
|
| 18 |
if t.TYPE_CHECKING: |
| 19 |
from ansible.module_utils.basic import AnsibleModule |
| 20 |
|
| 21 |
|
| 22 |
def online_argument_spec() -> dict[str, t.Any]: |
| 23 |
return dict( |
| 24 |
api_token=dict( |
| 25 |
required=True, |
| 26 |
fallback=(env_fallback, ["ONLINE_TOKEN", "ONLINE_API_KEY", "ONLINE_OAUTH_TOKEN", "ONLINE_API_TOKEN"]), |
| 27 |
no_log=True, |
| 28 |
aliases=["oauth_token"], |
| 29 |
), |
| 30 |
api_url=dict( |
| 31 |
fallback=(env_fallback, ["ONLINE_API_URL"]), default="https://api.online.net", aliases=["base_url"] |
| 32 |
), |
| 33 |
api_timeout=dict(type="int", default=30, aliases=["timeout"]), |
| 34 |
validate_certs=dict(default=True, type="bool"), |
| 35 |
) |
| 36 |
|
| 37 |
|
| 38 |
class OnlineException(Exception): |
| 39 |
def __init__(self, message: str) -> None: |
| 40 |
self.message = message |
| 41 |
|
| 42 |
|
| 43 |
class Response: |
| 44 |
def __init__(self, resp, info): |
| 45 |
self.body = None |
| 46 |
if resp: |
| 47 |
self.body = resp.read() |
| 48 |
self.info = info |
| 49 |
|
| 50 |
@property |
| 51 |
def json(self): |
| 52 |
if not self.body: |
| 53 |
if "body" in self.info: |
| 54 |
return json.loads(self.info["body"]) |
| 55 |
return None |
| 56 |
try: |
| 57 |
return json.loads(self.body) |
| 58 |
except ValueError: |
| 59 |
return None |
| 60 |
|
| 61 |
@property |
| 62 |
def status_code(self): |
| 63 |
return self.info["status"] |
| 64 |
|
| 65 |
@property |
| 66 |
def ok(self): |
| 67 |
return self.status_code in ( |
| 68 |
HTTPStatus.OK, |
| 69 |
HTTPStatus.CREATED, |
| 70 |
HTTPStatus.ACCEPTED, |
| 71 |
HTTPStatus.NO_CONTENT, |
| 72 |
) |
| 73 |
|
| 74 |
|
| 75 |
class Online: |
| 76 |
def __init__(self, module: AnsibleModule) -> None: |
| 77 |
self.module = module |
| 78 |
self.headers = { |
| 79 |
"Authorization": f"Bearer {self.module.params.get('api_token')}", |
| 80 |
"User-Agent": self.get_user_agent_string(module), |
| 81 |
"Content-type": "application/json", |
| 82 |
} |
| 83 |
self.name = None |
| 84 |
|
| 85 |
def get_resources(self): |
| 86 |
results = self.get(f"/{self.name}") |
| 87 |
if not results.ok: |
| 88 |
raise OnlineException( |
| 89 |
f"Error fetching {self.name} ({self.module.params.get('api_url')}/{self.name}) [{results.status_code}: {results.json['message']}]" |
| 90 |
) |
| 91 |
|
| 92 |
return results.json |
| 93 |
|
| 94 |
def _url_builder(self, path): |
| 95 |
if path[0] == "/": |
| 96 |
path = path[1:] |
| 97 |
return f"{self.module.params.get('api_url')}/{path}" |
| 98 |
|
| 99 |
def send(self, method, path, data=None, headers=None): |
| 100 |
url = self._url_builder(path) |
| 101 |
data = self.module.jsonify(data) |
| 102 |
|
| 103 |
if headers is not None: |
| 104 |
self.headers.update(headers) |
| 105 |
|
| 106 |
resp, info = fetch_url( |
| 107 |
self.module, |
| 108 |
url, |
| 109 |
data=data, |
| 110 |
headers=self.headers, |
| 111 |
method=method, |
| 112 |
timeout=self.module.params.get("api_timeout"), |
| 113 |
) |
| 114 |
|
| 115 |
# Exceptions in fetch_url may result in a status -1, the ensures a proper error to the user in all cases |
| 116 |
if info["status"] == -1: |
| 117 |
self.module.fail_json(msg=info["msg"]) |
| 118 |
|
| 119 |
return Response(resp, info) |
| 120 |
|
| 121 |
@staticmethod |
| 122 |
def get_user_agent_string(module): |
| 123 |
return f"ansible {module.ansible_version} Python {sys.version.split(' ', 1)[0]}" |
| 124 |
|
| 125 |
def get(self, path, data=None, headers=None): |
| 126 |
return self.send("GET", path, data, headers) |
| 127 |
|
| 128 |
def put(self, path, data=None, headers=None): |
| 129 |
return self.send("PUT", path, data, headers) |
| 130 |
|
| 131 |
def post(self, path, data=None, headers=None): |
| 132 |
return self.send("POST", path, data, headers) |
| 133 |
|
| 134 |
def delete(self, path, data=None, headers=None): |
| 135 |
return self.send("DELETE", path, data, headers) |
| 136 |
|
| 137 |
def patch(self, path, data=None, headers=None): |
| 138 |
return self.send("PATCH", path, data, headers) |
| 139 |
|
| 140 |
def update(self, path, data=None, headers=None): |
| 141 |
return self.send("UPDATE", path, data, headers) |