-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdigitalocean.py
93 lines (77 loc) · 2.38 KB
/
digitalocean.py
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
82
83
84
85
86
87
88
89
90
91
92
93
import requests
import os
import uuid
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.environ.get("DIGITALOCEAN_TOKEN")
ApiError = type("ApiError", (Exception,), {})
def list_droplets():
res = requests.get(
"https://api.digitalocean.com/v2/droplets",
headers={"Authorization": f"Bearer {TOKEN}"},
)
if res.status_code != 200:
raise ApiError(res.json())
return res.json()["droplets"]
def create_droplet(ssh_key):
res = requests.post(
"https://api.digitalocean.com/v2/droplets",
headers={
"Authorization": f"Bearer {TOKEN}",
"Content-Type": "application/json",
},
json={
"name": f"dodocker-{uuid.uuid4()}",
"region": "fra1",
"size": "s-1vcpu-1gb",
"image": "ubuntu-20-04-x64",
"ssh_keys": [ssh_key],
},
)
if res.status_code != 202:
raise ApiError(res.json())
return res.json()["droplet"]
def delete_droplet(droplet_name):
droplets = list_droplets()
droplet_id = None
for droplet in droplets:
if droplet["name"] == droplet_name:
droplet_id = droplet["id"]
break
if droplet_id is None:
raise ApiError(f"Droplet {droplet_name} not found")
res = requests.delete(
f"https://api.digitalocean.com/v2/droplets/{droplet_id}",
headers={"Authorization": f"Bearer {TOKEN}"},
)
if res.status_code != 204:
raise ApiError(res.json())
return 0
def add_ssh_key(name, pem_string):
res = requests.post(
"https://api.digitalocean.com/v2/account/keys",
headers={
"Authorization": f"Bearer {TOKEN}",
"Content-Type": "application/json",
},
json={"name": name, "public_key": pem_string},
)
if res.status_code != 201:
raise ApiError(res.json())
return 0
def list_ssh_keys():
res = requests.get(
"https://api.digitalocean.com/v2/account/keys",
headers={"Authorization": f"Bearer {TOKEN}"},
)
if res.status_code != 200:
raise ApiError(res.json())
return res.json()["ssh_keys"]
def delete_ssh_key(key_id):
res = requests.delete(
f"https://api.digitalocean.com/v2/account/keys/{key_id}",
headers={"Authorization": f"Bearer {TOKEN}"},
)
if res.status_code != 204:
raise ApiError(res.json())
return 0