summaryrefslogtreecommitdiff
path: root/plugins/httpapi/vyos.py
blob: 934026117fc6b2b8da4fd01c51616604dc1d4d26 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import json

from urllib.parse import urlencode

from ansible.plugins.httpapi import HttpApiBase


DOCUMENTATION = r"""
---
httpapi: vyos
short_description: VyOS REST API
description:
  - HTTPAPI plugin for interacting with VyOS REST API.
author: Evgeny Molotkov (@eomnom62)
options:
  api_key:
    description: VyOS API key
    type: str
    vars:
      - name: ansible_httpapi_api_key
    env:
      - name: ANSIBLE_HTTPAPI_API_KEY
    ini:
      - section: httpapi
        key: api_key
"""


class HttpApi(HttpApiBase):

    def set_options(self, task_keys=None, var_options=None, direct=None):
        super().set_options(
            task_keys=task_keys,
            var_options=var_options,
            direct=direct,
        )

    def send_request(self, path, data=None, method="POST", headers=None):

        api_key = self.get_option("api_key")

        if not api_key:
            # fallback to inventory vars
            api_key = self._play_context.vars.get("ansible_httpapi_api_key")

        if not api_key:
            raise ValueError("api_key is required")

        form_data = {}

        if data is not None:
            if not isinstance(data, str):
                data = json.dumps(data)
            form_data["data"] = data

        form_data["key"] = api_key

        body = urlencode(form_data).encode("utf-8")

        if headers is None:
            headers = {}

        headers["Content-Type"] = "application/x-www-form-urlencoded"

        status, response = self.connection.send(
            path,
            body,
            method=method,
            headers=headers,
        )

        if hasattr(response, "read"):
            response = response.read()

        if isinstance(response, bytes):
            response = response.decode("utf-8")

        if isinstance(response, str):
            response = json.loads(response)

        return response