Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a curated output flag for inventory #311

Merged
merged 1 commit into from
Sep 9, 2024
Merged
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
27 changes: 23 additions & 4 deletions broker/commands.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
"""Defines the CLI commands for Broker."""

from functools import wraps
import signal
import sys

import click
from logzero import logger
from rich.console import Console
from rich.table import Table

from broker import exceptions, helpers, settings
from broker.broker import Broker
Expand Down Expand Up @@ -267,13 +270,14 @@ def checkin(vm, background, all_, sequential, filter):

@loggedcli()
@click.option("--details", is_flag=True, help="Display all host details")
@click.option("--curated", is_flag=True, help="Display curated host details")
@click.option(
"--sync",
type=str,
help="Class-style name of a supported broker provider. (AnsibleTower)",
)
@click.option("--filter", type=str, help="Display only what matches the specified filter")
def inventory(details, sync, filter):
def inventory(details, curated, sync, filter):
"""Get a list of all VMs you've checked out showing hostname and local id.

hostname pulled from list of dictionaries.
Expand All @@ -282,9 +286,25 @@ def inventory(details, sync, filter):
Broker.sync_inventory(provider=sync)
logger.info("Pulling local inventory")
inventory = helpers.load_inventory(filter=filter)
emit_data = []
helpers.emit({"inventory": inventory})
if curated:
console = Console()
table = Table(title="Host Inventory")

table.add_column("Id", justify="left", style="cyan", no_wrap=True)
table.add_column("Host", justify="left", style="magenta")
table.add_column("Provider", justify="left", style="green")
table.add_column("Action", justify="left", style="yellow")
table.add_column("OS", justify="left", style="blue")
Comment on lines +294 to +298
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we also add the name of the host to the table? There are quite a lot of cases when I need both, a hostname and the name of the host.

This ask might be a personal preference, however as I spoke with @lpramuk, he would also like to see what instance of the given provider was used to deploy the host.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd like to keep this table small, and not replicate the details view. So for now, I do want to stick with these columns, but look into ways to make it customizable in the future.


for host in helpers.get_host_inventory_fields(inventory, PROVIDERS):
table.add_row(
str(host["id"]), host["host"], host["provider"], host["action"], host["os"]
)

console.print(table)
return
for num, host in enumerate(inventory):
emit_data.append(host)
if (display_name := host.get("hostname")) is None:
display_name = host.get("name")
# if we're filtering, then don't show an index.
Expand All @@ -294,7 +314,6 @@ def inventory(details, sync, filter):
logger.info(f"{index}{display_name}:\n{helpers.yaml_format(host)}")
else:
logger.info(f"{index}{display_name}")
helpers.emit({"inventory": emit_data})


@loggedcli()
Expand Down
42 changes: 42 additions & 0 deletions broker/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,48 @@ def yaml_format(in_struct):
return yaml.dump(in_struct, default_flow_style=False, sort_keys=False)


def get_checkout_options(provider_cls):
"""Return the checkout options for a provider."""
options = []
# iterate through the _checkout_options list
for option in provider_cls._checkout_options:
# now we need to dig into the baked-in attributes of the click decorator
for param in option.__closure__:
if isinstance(param.cell_contents, tuple):
for opt in param.cell_contents:
if opt.startswith("--"):
options.append(opt[2:].replace("-", "_")) # noqa: PERF401
return options


def get_host_inventory_fields(inv_dict, providers):
"""Get a more focused set of fields from the host inventory."""
curated_hosts = []
for num, host in enumerate(inv_dict):
match host:
case {
"name": name,
"hostname": hostname,
"_broker_provider": provider,
}:
os_name = host.get("os_distribution", "Unknown")
os_version = host.get("os_distribution_version", "")
checkout_opts = get_checkout_options(providers[provider])
for opt in checkout_opts:
if action := host["_broker_args"].get(opt):
curated_hosts.append(
{
"id": num,
"host": hostname or name,
"provider": provider,
"os": f"{os_name} {os_version}",
"action": action,
}
)
break
return curated_hosts


def kwargs_from_click_ctx(ctx):
"""Convert a Click context object to a dictionary of keyword arguments."""
# if users use `=` to note arg=value assignment, then we need to split it
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ dependencies = [
"logzero",
"packaging",
"pyyaml",
"rich",
"setuptools",
"ssh2-python312",
]
Expand Down