Skip to content

Instantly share code, notes, and snippets.

@mhewedy
Last active March 24, 2022 12:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhewedy/1229d249e7085f7cd6d73c3f725c0903 to your computer and use it in GitHub Desktop.
Save mhewedy/1229d249e7085f7cd6d73c3f725c0903 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import subprocess
import sys
SCW_TYPE = 'DEV1-S'
SCW_ZONE = 'nl-ams-1'
SCW_IMAGE = 'centos_8'
SCW_PROJECT_ID = '<projectid>'
LOG_CMD = False
def exec_cmd(c):
if LOG_CMD: print(c)
subprocess.call(c.split())
def do_create():
for i in range(1, 4):
exec_cmd(
f'scw instance server create type={SCW_TYPE} zone={SCW_ZONE} image={SCW_IMAGE}'
f' name=node{i:02} ip=new project-id={SCW_PROJECT_ID}'
)
def do_list():
exec_cmd(f'scw instance server list zone={SCW_ZONE}')
def do_delete():
def list_server_ids():
cmd = f"scw instance server list zone={SCW_ZONE} | tail -n +2 | awk '{{print $1}}'"
out = subprocess.check_output(cmd, shell=True).splitlines()
return [b.decode('UTF-8') for b in out]
ids = list_server_ids()
if not ids:
print(f'no servers found in zone: {SCW_ZONE}')
return
for server_id in ids:
exec_cmd(f'scw instance server delete {server_id} zone={SCW_ZONE} force-shutdown=true')
def main():
command = sys.argv[1] if len(sys.argv) > 1 else None
if command == 'create':
do_create()
elif command == 'delete':
do_delete()
elif command == 'list':
do_list()
else:
print('invalid command')
if __name__ == '__main__':
main()
@h4dying
Copy link

h4dying commented Mar 22, 2022

We could refactor the main function to something like that:

def main():
    command = sys.argv[1] if len(sys.argv) > 1 else None
    commands = {
        "create": do_create,
        "delete": do_delete,
        "list": do_list
    }
    try:
        commands[command]()
    except KeyError:
        print('invalid command')
     

@mhewedy
Copy link
Author

mhewedy commented Mar 23, 2022

@ahm3dmelh4dy
Wow, I like it... Thanks for the update 👍

Can we avoid try catch by using get or using an if gaurd?

@h4dying
Copy link

h4dying commented Mar 23, 2022

Yeah, I think we could do something like that:

def main():
    command = sys.argv[1] if len(sys.argv) > 1 else None
    commands = {
        "create": do_create,
        "delete": do_delete,
        "list": do_list
    }

    # set a default value to return if the key is not found.
    error_msg = "invalid command"
    result = commands.get(command, error_msg)
    
    if result == error_msg:
        print(result)
    else:
        result()

@mhewedy
Copy link
Author

mhewedy commented Mar 24, 2022

@ahm3dmelh4dy ❤️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment