🩹 Update utility functions

This commit is contained in:
Neill Cox 2023-10-18 08:33:26 +11:00
parent 80830e5e68
commit 3ed2e4a029

View file

@ -1,31 +1,62 @@
"""Utility functions"""
import json
import os
import subprocess
import sys
def get_from_env(name, envvar, required=True):
"""Get the value for a parameter from an environment variable"""
value = os.environ.get(envvar)
if value is None and required:
print(
f"You must specify {name}, either on the commandline or using "
f"the {envvar} environment varauble."
)
)
sys.exit(1)
return value
def openstack_cmd(cmd, args):
def openstack_cmd(cmd, args, as_json=False):
"""Utility function to run an openstack command agains the standalone cloud"""
cmd = cmd.replace("\n", " ")
cmd = "OS_CLOUD=standalone openstack " + cmd
if args.ssh:
cmd = f"ssh {args.ssh} \"{cmd}\""
cmd = f'ssh {args.ssh} "{cmd}"'
if args.dry_run:
print("dry-run specified. Not executing cmd. cmd was:")
print(cmd)
return
return None
result = subprocess.check_output(cmd, shell=True, universal_newlines=True)
try:
result = subprocess.check_output(cmd, shell=True, universal_newlines=True)
if as_json:
result = json.loads(result)
except subprocess.CalledProcessError as err:
print("Cmd failed")
print(f"cmd: {cmd}")
print(f"return code: {err.returncode}")
print(f"stderr: {err.stderr}")
print(f"stdout: {err.output}")
sys.exit(1)
return result
def test_user_openstack_cmd(cmd, args, as_json=False):
"""Run an openstack command as the test user"""
cmd = (
f"--os-project-id {args.project_id} "
f"--os-username {args.username} "
f"--os-password {args.password} "
) + cmd
if args.debug:
print(cmd)
return openstack_cmd(cmd, args, as_json=as_json)