summaryrefslogtreecommitdiff
path: root/plugins/httpapi/vyos.py
blob: 049ef971f2f9827050eb06bcb5d9a0fd8cc1260b (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
from ansible.plugins.httpapi import HttpApiBase
from urllib.parse import urlencode
import json


DOCUMENTATION = r'''
---
httpapi: vyos
short_description: VyOS REST API
description:
  - HTTPAPI plugin for interacting with VyOS REST API.
options:
  api_key:
    description: VyOS API key
    required: true
    type: str
    vars:
      - name: ansible_httpapi_api_key
    env:
      - name: ANSIBLE_HTTPAPI_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")

        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