🩹 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,8 +1,12 @@
"""Utility functions"""
import json
import os import os
import subprocess import subprocess
import sys import sys
def get_from_env(name, envvar, required=True): def get_from_env(name, envvar, required=True):
"""Get the value for a parameter from an environment variable"""
value = os.environ.get(envvar) value = os.environ.get(envvar)
if value is None and required: if value is None and required:
@ -14,18 +18,45 @@ def get_from_env(name, envvar, required=True):
return value 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""" """Utility function to run an openstack command agains the standalone cloud"""
cmd = cmd.replace("\n", " ")
cmd = "OS_CLOUD=standalone openstack " + cmd cmd = "OS_CLOUD=standalone openstack " + cmd
if args.ssh: if args.ssh:
cmd = f"ssh {args.ssh} \"{cmd}\"" cmd = f'ssh {args.ssh} "{cmd}"'
if args.dry_run: if args.dry_run:
print("dry-run specified. Not executing cmd. cmd was:") print("dry-run specified. Not executing cmd. cmd was:")
print(cmd) print(cmd)
return return None
try:
result = subprocess.check_output(cmd, shell=True, universal_newlines=True) 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 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)