Adding digital ocean rest api
-import subprocess
-import json
+import os
import functools
+import requests
-@functools.lru_cache()
-def instances():
- output = subprocess.check_output(
- ["doctl", "kubernetes", "options", "sizes", "-o=json"]
+
+def digital_ocean_request(url, method="GET", json=None):
+ BASE_DIGITALOCEAN_URL = "https://api.digitalocean.com/v2/"
+
+ for name in {"DIGITALOCEAN_TOKEN"}:
+ if name not in os.environ:
+ raise ValueError(
+ f"Digital Ocean api requests require environment variable={name} defined"
)
- data = json.loads(output.decode("utf-8"))
- return {_["name"]: _["slug"] for _ in data}
+ headers = {"Authorization": f'Bearer {os.environ["DIGITALOCEAN_TOKEN"]}'}
-@functools.lru_cache()
-def regions():
- output = subprocess.check_output(
- ["doctl", "kubernetes", "options", "regions", "-o=json"]
+ method_map = {
+ "GET": requests.get,
+ }
+
+ response = method_map[method](
+ f"{BASE_DIGITALOCEAN_URL}{url}", headers=headers, json=json
)
- data = json.loads(output.decode("utf-8"))
- return {_["name"]: _["slug"] for _ in data}
+ response.raise_for_status()
+ return response
@functools.lru_cache()
+def _kubernetes_options():
+ return digital_ocean_request("kubernetes/options").json()
+
+
+def instances():
+ return _kubernetes_options()["options"]["sizes"]
+
+
+def regions():
+ return _kubernetes_options()["options"]["regions"]
+
+
def kubernetes_versions():
- output = subprocess.check_output(
- ["doctl", "kubernetes", "options", "versions", "-o=json"]
- )
- data = json.loads(output.decode("utf-8"))
- return {_["kubernetes_version"]: _["slug"] for _ in data}
+ return _kubernetes_options()["options"]["kubernetes_version"]
