From 3ed2e4a02903b5ea375121f7c7bf6ffe3bd8de41 Mon Sep 17 00:00:00 2001 From: Neill Cox Date: Wed, 18 Oct 2023 08:33:26 +1100 Subject: [PATCH] :adhesive_bandage: Update utility functions --- src/tripleo_aio_helpers/utils.py | 45 +++++++++++++++++++++++++++----- 1 file changed, 38 insertions(+), 7 deletions(-) diff --git a/src/tripleo_aio_helpers/utils.py b/src/tripleo_aio_helpers/utils.py index 6906973..dfd5eab 100644 --- a/src/tripleo_aio_helpers/utils.py +++ b/src/tripleo_aio_helpers/utils.py @@ -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 - - result = subprocess.check_output(cmd, shell=True, universal_newlines=True) + return None + + 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)