-
-
Save mhewedy/1229d249e7085f7cd6d73c3f725c0903 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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() |
@ahm3dmelh4dy
Wow, I like it... Thanks for the update 👍
Can we avoid try catch by using get or using an if gaurd?
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()
@ahm3dmelh4dy ❤️
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We could refactor the main function to something like that: