Browse Source

add linode abstraction to simplify readability

Steven Jacobs 2 years ago
parent
commit
bc014aeb6f
1 changed files with 19 additions and 9 deletions
  1. 19 9
      bin/rebuild

+ 19 - 9
bin/rebuild

@@ -8,7 +8,15 @@ from urllib import request
 from urllib import error
 
 
-def linode_rebuild(args):
+BASE_URL = 'https://api.linode.com/v4'
+
+
+class Linode:
+    def __init__(self, id):
+        self.id = id
+        self.url = '{}/linode/instances/{}'.format(BASE_URL, self.id)
+
+def linode_rebuild(instance, args):
     root_pass = getpass.getpass(prompt='root password: ')
 
     query_args = {
@@ -17,7 +25,7 @@ def linode_rebuild(args):
         'booted': False,
     }
 
-    r = request.Request('https://api.linode.com/v4/linode/instances/{}/rebuild'.format(args.linode_id))
+    r = request.Request('{}/rebuild'.format(instance.url))
     r.add_header('content-type', 'application/json')
     r.add_header('Authorization', 'Bearer {}'.format(args.api_token))
     r.data = json.dumps(query_args).encode('utf-8')
@@ -25,7 +33,7 @@ def linode_rebuild(args):
 
     return request.urlopen(r).read().decode('utf-8')
 
-def linode_create_config(config, args):
+def linode_create_config(instance, config, args):
     query_args = {
         'kernel': 'linode/grub2',
         'devices': {
@@ -42,7 +50,7 @@ def linode_create_config(config, args):
         }
     }
 
-    r = request.Request('https://api.linode.com/v4/linode/instances/{}/configs/{}'.format(args.linode_id, config['id']))
+    r = request.Request('{}/configs/{}'.format(instance.url, config['id']))
     r.add_header('content-type', 'application/json')
     r.add_header('Authorization', 'Bearer {}'.format(args.api_token))
     r.data = json.dumps(query_args).encode('utf-8')
@@ -50,8 +58,8 @@ def linode_create_config(config, args):
 
     print(request.urlopen(r).read().decode('utf-8'))
 
-def linode_boot(args):
-    r = request.Request('https://api.linode.com/v4/linode/instances/{}/boot'.format(args.linode_id))
+def linode_boot(instance, args):
+    r = request.Request('{}/boot'.format(instance.url))
     r.add_header('Authorization', 'Bearer {}'.format(args.api_token))
     r.method = 'POST'
 
@@ -68,16 +76,18 @@ parser.add_argument('-b', '--boot', action='store_true',
 
 args = parser.parse_args()
 
+target = Linode(args.linode_id)
+
 try:
-    result = json.loads(linode_rebuild(args))
+    result = json.loads(linode_rebuild(target, args))
     config = result['configs'][0]
 except error.HTTPError as e:
     print(e.read())
 
 try:
-    linode_create_config(config, args)
+    linode_create_config(target, config, args)
 except error.HTTPError as e:
     print(e.read())
 
 if(args.boot):
-    linode_boot(args)
+    linode_boot(target, args)