Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 3 additions & 25 deletions osism/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,34 +31,12 @@
from osism.services.listener import BaremetalEvents
from osism.services.websocket_manager import websocket_manager
from osism.services.event_bridge import event_bridge
from osism.tasks.conductor.utils import _is_secret_key
from osism.utils.secrets import mask_structure


def _mask_inventory_secrets(data: dict) -> dict:
"""Mask secret values in inventory data before returning via API.

Masks values for keys matching secret patterns (password, secret,
ironic_osism_*) and values that are Ansible Vault encrypted, at any
nesting depth inside dicts and lists.
"""
masked: dict = {}
for key, value in data.items():
if _is_secret_key(key):
masked[key] = "***"
else:
masked[key] = _mask_inventory_value(value)
return masked


def _mask_inventory_value(value):
"""Mask secrets in a single inventory value, recursing into containers."""
if isinstance(value, str) and value.strip().startswith("$ANSIBLE_VAULT;"):
return "***"
if isinstance(value, dict):
return _mask_inventory_secrets(value)
if isinstance(value, list):
return [_mask_inventory_value(item) for item in value]
return value
"""Mask secret values in inventory data before returning via API."""
return mask_structure(data, mask="***")


class NotificationBaremetal(BaseModel):
Expand Down
182 changes: 178 additions & 4 deletions osism/commands/get.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,18 @@
import pprint
import re
import subprocess
import sys
import json

from cliff.command import Command
from loguru import logger
from tabulate import tabulate

from osism import utils
from osism import settings, utils
from osism.utils import fact_cache
from osism.utils.hostvars import HostvarsError, Row, effective_rows
from osism.utils.inventory import get_hosts_from_inventory, get_inventory_path
from osism.utils.render import list_environments


class VersionsManager(Command):
Expand Down Expand Up @@ -109,6 +112,10 @@ def take_action(self, parsed_args):
)


# The rendered path looks the name up; it is never templated.
VARIABLE_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")


class Hostvars(Command):
def get_parser(self, prog_name):
parser = super(Hostvars, self).get_parser(prog_name)
Expand All @@ -124,26 +131,121 @@ def get_parser(self, prog_name):
type=str,
help="Name of a variable to show",
)
environments = list_environments()
available = (
", ".join(environments)
if environments
else f"(none found under {settings.ENVIRONMENTS_DIRECTORY})"
)
parser.add_argument(
"--environment",
type=str,
help="Render with this environment only. Available: " + available,
)
parser.add_argument(
"--raw",
default=False,
help="Show values as defined, without rendering templates",
action="store_true",
)
parser.add_argument(
"--show-secrets",
default=False,
help="Show values that are secrets or derived from secrets",
action="store_true",
)
parser.add_argument(
"--format",
choices=["table", "value", "json"],
default="table",
help="Output format (default: table)",
)
return parser

def take_action(self, parsed_args):
host = parsed_args.host[0]
variable = parsed_args.variable

if (
not parsed_args.raw
and variable is not None
and not VARIABLE_NAME.fullmatch(variable)
):
logger.error(
f"not a valid variable name: {variable} "
"(letters, digits and underscores, not starting with a digit)"
)
return 1

inventory_path = get_inventory_path(
"/ansible/inventory/hosts.yml", prefer_minified=False
)
try:
result = subprocess.check_output(
f"ansible-inventory -i {inventory_path} --host {host}",
shell=True,
["ansible-inventory", "-i", inventory_path, "--host", host],
stderr=subprocess.DEVNULL,
)
except subprocess.CalledProcessError:
logger.error(f"Host {host} not found in inventory.")
return 1

data = json.loads(result)
raw_hostvars = json.loads(result)

if parsed_args.raw:
return self._take_raw(parsed_args, host, variable, raw_hostvars)

try:
vault_password = utils.get_ansible_vault_password()
except Exception as exc: # pylint: disable=broad-except
logger.error(
f"Cannot render: vault password unavailable ({type(exc).__name__}); "
"use --raw to see values as defined."
)
return 1

try:
all_raw_hostvars = json.loads(
subprocess.check_output(
["ansible-inventory", "-i", inventory_path, "--list"],
stderr=subprocess.DEVNULL,
)
)["_meta"]["hostvars"]
except (subprocess.CalledProcessError, ValueError, KeyError):
logger.error("Cannot render: the inventory could not be listed.")
return 1

facts = fact_cache.get_host_facts(utils.redis, host)

try:
rows = effective_rows(
host,
variable,
parsed_args.environment,
parsed_args.show_secrets,
inventory_path=inventory_path,
vault_password=vault_password,
facts=facts,
raw_hostvars=raw_hostvars,
all_raw_hostvars=all_raw_hostvars,
)
except HostvarsError as exc:
logger.error(str(exc))
return 1

return self._output(parsed_args, host, variable, rows)

def _take_raw(self, parsed_args, host, variable, data):
if parsed_args.format != "table":
if variable and variable not in data:
rows = []
else:
names = [variable] if variable else list(data)
rows = [
Row(host, name, None, data[name], False, [], False)
for name in names
]
return self._output(parsed_args, host, variable, rows)

table = []

if variable:
Expand All @@ -164,6 +266,78 @@ def take_action(self, parsed_args):

return

def _output(self, parsed_args, host, variable, rows):
fmt = parsed_args.format

if fmt == "json":
print(
json.dumps(
[
{
"host": r.host,
"variable": r.variable,
"environment": r.environment,
"value": r.value,
"masked": r.masked,
"notes": r.notes,
}
for r in rows
],
default=str,
)
)
return 1 if variable and any(r.failed for r in rows) else None

if fmt == "value":
if not variable:
logger.error("--format value requires a variable name.")
return 1
if not rows:
return None
if len(rows) > 1:
names = ", ".join(r.environment or "default" for r in rows)
logger.error(
f"ambiguous: environments differ ({names}); pass --environment"
)
return 1
row = rows[0]
if row.masked:
reasons = "; ".join(
n.removeprefix("masked: ")
for n in row.notes
if n.startswith("masked: ")
)
logger.error(f"value is masked ({reasons}); pass --show-secrets")
return 1
if row.failed:
for note in row.notes:
print(note, file=sys.stderr)
return 1
print(row.value if isinstance(row.value, str) else json.dumps(row.value))
return None

if not rows:
if variable:
logger.error(f"Variable {variable} not found in inventory for {host}.")
return None

table = []
for r in rows:
label = f"{r.variable} [{r.environment}]" if r.environment else r.variable
if r.masked:
value = "***"
elif r.failed:
value = ""
else:
value = pprint.pformat(r.value, indent=2, width=60, compact=True)
table.append([r.host, label, value, "\n".join(r.notes)])
print(
tabulate(
table, headers=["Host", "Variable", "Value", "Notes"], tablefmt="grid"
)
)
return 1 if variable and any(r.failed for r in rows) else None


class Facts(Command):
def get_parser(self, prog_name):
Expand Down
5 changes: 5 additions & 0 deletions osism/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ def read_secret(secret_name):
"ANSIBLE_VAULT_KEYFILE", "/share/ansible_vault_password.key"
)

# Root of the configuration repository's environments, as `osism apply` sees it.
ENVIRONMENTS_DIRECTORY = os.getenv(
"ENVIRONMENTS_DIRECTORY", "/opt/configuration/environments"
)


NETBOX_URL = os.getenv("NETBOX_API", os.getenv("NETBOX_URL"))
NETBOX_TOKEN = str(
Expand Down
8 changes: 1 addition & 7 deletions osism/tasks/conductor/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from loguru import logger

from osism import utils
from osism.utils.secrets import is_secret_key as _is_secret_key # noqa: F401
import sushy
import urllib3
import yaml
Expand Down Expand Up @@ -294,13 +295,6 @@ def check_task_lock_and_exit():
return utils.check_task_lock_and_exit()


def _is_secret_key(key):
if not isinstance(key, str):
return False
lower = key.lower()
return "password" in lower or "secret" in lower or lower.startswith("ironic_osism_")


def mask_secrets(obj, mask="xxx", secret_values=None):
"""Return a deep copy of obj with secret values masked.

Expand Down
Loading