Skip to content

Render effective values in osism dump inventory - #2939

Draft
ideaship wants to merge 16 commits into
mainfrom
dump-inventory-render
Draft

ideaship wants to merge 16 commits into
mainfrom
dump-inventory-render

Conversation

@ideaship

Copy link
Copy Markdown
Contributor

osism dump inventory <host> [<variable>] (alias osism get hostvars) prints ansible-inventory --host output. That output is wrong in two ways:

  1. It does not template. mariadb_loadbalancer, ceph_image_version or a per-host radosgw_address: "192.168.16.{{ node_id }}" come back as the expression, not the value a play sees.
  2. It shows the losing layer. An override in environments/<env>/configuration.yml is invisible: enable_proxysql: yes in kolla's configuration shows as 'no'.

This PR renders effective values by default: the inventory plus the configuration repository's extra-vars files, stacked in the order the run scripts pass them, templated by Ansible in the host's context. It takes one controller-side Ansible run per stack, and makes no connection to the host.

Command surface

osism dump inventory <host> [<variable>]
    --environment <env>          render with that environment's stack only
    --raw                        values as defined; today's output, byte for byte
    --show-secrets               do not mask values derived from secrets
    --format table|value|json    default: table, with a Notes column

Without --environment, the unlabelled row is the value in every environment not listed separately. A variable [env] row is added for each environment whose files define the variable or anything it depends on.

Masking: what it protects against

The CLI runs where the vault and /ansible/secrets are, and osism vault view exists, so masking here is not access control. Today's raw output never shows a plaintext secret only because it never decrypts. Rendering does decrypt, so values derived from secrets are masked by default. That keeps them out of output that travels: tables pasted into issues or chats, CI and tool logs.

  • A value is masked when it is a secret or its dependency closure reaches one: secrets files, the key rule, vault values, followed through filters, vars/hostvars subscripts and dynamic keys that resolve. A literal-replacement net catches rendered secret values in any other value.
  • Out of scope: expressions written to defeat the analysis, such as vars['hostvars'][other]['ipmi_password'] or lookup('file', …) on a secrets file. Writing those into the configuration repository needs access that already gives the secrets. Such shapes are documented as limits.
  • The REST API keeps its own masking, unchanged.

Structure

  • osism/utils/secrets.py: masking shared by the API, the conductor and this command. The API and conductor output is unchanged.
  • osism/utils/template_deps.py: static Jinja reference extraction.
  • osism/utils/evaluate.py and osism/utils/render.py: closures and values in one Ansible run per stack.
  • osism/utils/hostvars.py and hostvars_rows.py: rows, environments, masking and notes.
  • run_in_host_context() in osism/utils/inventory.py is the one engine behind both the renderer and resolve_in_host_context() (RabbitMQ address lookup). Each keeps its own small action plugin, because the renderer needs ansible-core 2.19's trust_as_template, while the resolver also runs on 2.18.

Testing

  • Unit suite: 4190 passed.
  • Integration against real ansible-core 2.19.11 (OSISM_REQUIRE_ANSIBLE=1 pytest tests/integration/test_hostvars_render.py tests/integration/test_host_context_resolution.py -m integration): 14 passed.
  • Not yet: a live check on a deployed OSISM 11 cluster. Draft until that has run.

Documentation for get.md follows in a separate osism.github.io PR.

🤖 Generated with Claude Code

Extract secret detection and masking logic into a shared module
osism/utils/secrets.py to eliminate duplication between
osism/api.py and osism/tasks/conductor/utils.py.

The module provides:
- is_secret_key(key) -> bool: detects secret keys by name pattern
- is_vault_value(value) -> bool: detects vault-encrypted values
- mask_structure(data, mask="***") -> dict: recursively masks by key
  name and vault value
- replace_literals(text, secret_values, mask="***", min_length=0):
  replaces known secret values in text
- replace_literals_deep(obj, secret_values, mask="***", min_length=0):
  deep copy of obj with literal replacement

The conductor's mask_secrets and _mask_secrets_inplace functions keep
their original behavior and output; _is_secret_key is re-exported from
the shared module to maintain compatibility with existing tests
(mask="xxx" default). The API's masking functions are simplified to
call mask_structure, preserving their "***" mask and recursive behavior
at every nesting depth.

All 219 existing tests pass unchanged.

Assisted-by: Claude:claude-haiku-4-5-20251001
Signed-off-by: Roger Luethi <luethi@osism.tech>
Add a pure module that finds which variables a raw Ansible/Jinja value
refers to, without rendering it. It parses the value with
jinja2.Environment().parse() and walks the syntax tree itself.
jinja2.meta.find_undeclared_variables does not fit: it raises on
unknown filters and does not report subscript targets.

- Refs records static references (names), cross-host references
  (hostvars), dynamic keys, and whether the value is unanalysable.
- DynamicKey holds the expression of a subscript key that is not a
  constant, with a cross_host flag.
- references() recurses into dicts, lists and template strings.
- Names bound in the template ({% set %} targets and for loop
  variables) are tracked per scope in statement order, so earlier
  references are not hidden by later bindings.
- vars['X'], vars.X, hostvars[H]['X'], hostvars[H].X and hostvars.H.X
  are handled, and same-host references are told apart from cross-host
  ones.
- lookup/query/q() calls of the vars lookup are analysed for their
  targets.
- Unknown filters do not break the analysis. Unmodelled scopes (Macro,
  CallBlock, With, FilterBlock) and a TemplateSyntaxError make the
  value unanalysable.

Assisted-by: Claude:claude-haiku-4-5-20251001
Signed-off-by: Roger Luethi <luethi@osism.tech>
Effective values of an environment depend on the extra-vars files that
`osism apply` passes, and dependency closures contain dynamic keys such
as vars[n]. Resolving such a key can reach a variable that holds
another dynamic key, so a closure cannot be computed up front without
repeated Ansible runs.

Add an evaluation core (osism.utils.evaluate) that walks a closure and
resolves every dynamic key through a callback, and a renderer
(osism.utils.render) that runs it inside a single controller-side
Ansible invocation per host and stack. A small action plugin passes
Ansible's templar as the callback, so chained key resolution, values
and secret hits all come out of one run.

The renderer also builds the stack of files for an environment in the
order the standard run scripts use, and loads them vault-aware: whole
file vaults are decrypted, inline !vault values keep their provenance
as an encrypted marker. Errors name the file and line but never carry
file content. ENVIRONMENTS_DIRECTORY sets the root of the environments.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Roger Luethi <luethi@osism.tech>
`osism dump inventory` is to show the values a play would see. This
adds effective_rows, which turns per-stack render results into output
rows:

- shown names: the variable asked for, or the union of the host's raw
  names, the stack files' names and, without --environment, each
  environment's own names, so environment-only variables appear;
- one render per stack: the primary stack, plus each environment whose
  own files define a shown variable or a name in its dependency
  closure; for an unanalysable variable every environment is rendered
  and its row kept only if the value differs from the global one;
- an environment with a missing file, or whose files cannot be read,
  gives failed rows for its candidates only;
- the secret set S per stack: names in secrets.yml, names matching the
  key rule, and names whose value is vault-encrypted on any host.

Masking, unless --show-secrets: a variable in S or whose closure
reaches S is masked and the note names the secrets; an unanalysable one
is masked; otherwise every rendered secret value of 6 or more
characters is replaced in the value. The same replacement runs over
error and fallback notes. Error detail of a tainted or unanalysable
variable is withheld, as is Ansible's own output when a whole stack
fails, since that stack's secret values are then unknown. An unknown
--environment is rejected before any path is built from it.

Masking and row construction live in hostvars_rows.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Roger Luethi <luethi@osism.tech>
The secret set S of a stack missed two kinds of secrets, and their
values were printed unmasked:

- the key rule (password, secret, ironic_osism_) was applied only to
  the queried host's names. A read of another host's variable, such as
  hostvars['node2']['ipmi_password'] with a plaintext value in node2's
  host_vars, or a value derived from it, was not tainted;
- a vault value nested inside a dict or list was not detected, although
  Ansible decrypts it when templating the enclosing variable.

S now applies the key rule and the vault rule to every host's names,
and the vault rule walks dicts and lists to any depth.

The integration test pins the exact ansible-core error for an
undefined name, which the row builder matches to drop the row of an
absent variable.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Roger Luethi <luethi@osism.tech>
"osism dump inventory" (alias "osism get hostvars") used to print
the values exactly as defined, so templated values such as
"{{ foo }}" were shown unevaluated. It now renders effective
values by default, using the engine in osism.utils.hostvars.

New options:

  --environment ENV  render with this environment only; the help
                     lists the available environments
  --raw              today's output, unchanged byte for byte
  --show-secrets     show values that are secrets or derived from
                     secrets
  --format           table (default, with a Notes column), value
                     or json

Values that are secrets, or derived from secrets, are masked as
"***" unless --show-secrets is given. If the vault password is
unavailable the command exits 1 and points to --raw; the
exception text is never printed.

Exit codes: an absent variable is 0 (json prints []); an unknown
host, unknown environment, unavailable vault password or primary
stack failure is 1, as is a failed row when a single variable is
requested. A full dump with failed rows exits 0 and shows the
failures in Notes. "--format value" exits 1 when the result is
ambiguous across environments, masked or failed.

Both ansible-inventory calls now use an argv list instead of a
shell string, so host names are no longer interpreted by a shell.

Scope limits: only the effective values of the selected host are
rendered; templates that need runtime-only data may fall back
and say so in Notes. See the osism documentation for details.

Assisted-by: Claude:claude-sonnet-5-5
Signed-off-by: Roger Luethi <luethi@osism.tech>
The dependency walker ignored the names vars and hostvars unless they
were the base of a constant subscript or attribute. Other uses reached
secrets without the value being masked: lookup('ansible.builtin.vars',
...), hostvars[h].get(...), map('extract', vars|hostvars, ...) and an
alias such as {% set v = vars %} all rendered a secret, or its base64,
in the clear.

vars and hostvars are now modelled only as the base of a subscript or
attribute, of .get(key), of lookup/query('vars', ...) under the names
vars, ansible.builtin.vars and ansible.legacy.vars, and of
map('extract', ...). With hostvars, the first component of the extract
key is a cross-host reference; with vars, the constant items of the
mapped list are the referenced names. Any other use (the bare name, an
alias, a mapping method such as vars.items(), hostvars[h] on its own,
*args) can reach every variable, so the value is masked as
unanalysable.

An integration test renders the leaking shapes with real Ansible on a
two-host inventory and asserts that no plaintext or base64 secret
reaches the rows.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Roger Luethi <luethi@osism.tech>
is_vault_value treats an inline vault value, {"__ansible_vault": ...},
as a vault value. mask_structure used it, so the API's inventory
masking changed its output from {'x': {'__ansible_vault': '***'}} to
{'x': '***'}. The API must keep its output.

mask_structure gets a structural_vault parameter. Its default, False,
is the API's old rule: a vault value is a string with the vault
header, so an inline vault dict keeps its shape and only its
ciphertext is masked. structural_vault=True applies is_vault_value and
masks the whole inline vault dict.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Roger Luethi <luethi@osism.tech>
A rendered value got a "fallback: <name> undefined here" note for every
undefined name in its dependency closure as soon as the string
"default(" occurred anywhere in a raw value. Cached facts are passed to
Ansible but were not counted as defined. So osism/defaults'
internal_address, "{{ ansible_default_ipv4.address|default(
ansible_all_ipv4_addresses[0]) }}", rendered from facts and still got
two false fallback notes; the d alias was not recognised at all.

The request now carries the queried host's fact names, which count as
defined in the closure walk. The dependency walker records the names
(and dynamic keys) referenced inside a default or d filter's base or
argument, in nested dict and list values too. A closure reports
"fallback", the undefined names among them, instead of the
uses_default flag, and only those get a fallback note.

An integration test covers an undefined name with a default on real
Ansible.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Roger Luethi <luethi@osism.tech>
A value tagged !unsafe in an environments file made the command exit 1:
the vault-aware SafeLoader had no constructor for the tag and raised a
ConstructorError.

The loader now constructs such a value as UnsafeText, a str subclass.
The dependency walker never parses it as a template, since Ansible
never templates it either. The closure walk runs inside the action
plugin, and JSON turns a str subclass into a plain str, so the request
carries the tag as {"__ansible_unsafe": text}, which the walker skips
too. Ansible reads the stack files itself, so the rendered value is
unaffected.

ansible-inventory drops the tag from inventory values; those are still
analysed as templates.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Roger Luethi <luethi@osism.tech>
render_batch passed the cached facts file as the last -e argument. A
later -e wins, so a fact outranked the environments files, while in a
play extra-vars outrank facts: a name defined both as a fact and in
the configuration repository rendered as the fact.

The facts file now goes first, giving inventory < facts < stack files.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Roger Luethi <luethi@osism.tech>
An ANSIBLE_FORCE_COLOR setting inherited from the caller's environment
makes Ansible colour its output even with ANSIBLE_NOCOLOR=1. The ANSI
escapes then end up in the error detail a render failure shows.

The render subprocess now runs with ANSIBLE_FORCE_COLOR=0.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Roger Luethi <luethi@osism.tech>
A variable's value was rendered by templating "{{ <name> }}". A name
that is not an identifier was therefore evaluated as an expression: an
environments key 'plain ~ 2' rendered as 12, and the CLI's variable
argument could combine other variables, secrets included, into one
expression.

Values are now looked up as vars['<name>']. An absent name makes that
lookup fail with Jinja's "has no attribute" message, so
"'<name>' in vars" is checked first and an absent name is reported as
"AnsibleUndefinedVariable: '<name>' is undefined", the shape the rows
code relies on to drop the row of an absent variable. Dynamic keys
found in templates are still templated as expressions.

The command also refuses a variable argument that is not an identifier
([A-Za-z_][A-Za-z0-9_]*) and exits 1. --raw is unaffected; it never
templates.

The unit-test fakes answer the new expressions through a small
by_name adapter.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Roger Luethi <luethi@osism.tech>
When only the literal net changed a value, the row was marked masked
but carried no note saying why. It now gets the note
"masked: contains a secret value".

The refusal of --format value for a masked row repeated the prefix,
"value is masked (masked: derived from p)". It now lists the masked
notes without their "masked: " prefix:
"value is masked (derived from p); pass --show-secrets".

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Roger Luethi <luethi@osism.tech>
The table output printed None in the Value column of a row whose
render failed. The cell is now empty; the row's note carries the
failure.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Roger Luethi <luethi@osism.tech>
resolve_in_host_context() and the batch renderer of osism dump
inventory (osism/utils/render.py) both run a controller-side action
plugin through "ansible <host> -c local" and read its result back from
a file. Each carried its own copy of everything around the plugin: the
temporary directory, the plugin installation, the environment, the
extra-vars files, the subprocess call, the error handling and the
readback. The copies had already drifted: only the renderer ran from a
neutral working directory, closed stdin and overrode
ANSIBLE_FORCE_COLOR.

run_in_host_context() in osism/utils/inventory.py is now the one
engine. Both callers keep their own plugin, because what they template
differs: the resolver's plugin writes one templated module argument and
must keep working on ansible-core 2.18, while the renderer's plugin
uses the 2.19 templar API (trust_as_template). The engine:

- installs the plugin into a temporary directory that is also the
  working directory, so no group_vars/ next to the caller's current
  directory is loaded
- never gathers facts, closes stdin and forces colour off
- passes facts as an extra-vars file before any other extra-vars files,
  since a later -e wins and extra vars outrank facts in a play
- passes optional request data as a file, so Ansible does not template
  it, and an optional vault password as a 0600 password file
- returns the text the plugin wrote

HostContextResolutionError gains from_ansible, set when the message is
Ansible's own output. The renderer maps it to RenderError.safe, which
decides whether the detail may be shown without --show-secrets.

resolve_in_host_context() now also runs from the neutral working
directory with stdin closed. Its signature, its return value and its
unit and integration tests are unchanged; the renderer's tests now
patch the engine's subprocess call.

Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Roger Luethi <luethi@osism.tech>
@ideaship
ideaship force-pushed the dump-inventory-render branch from 086ff85 to 65e4eb5 Compare November 27, 2026 16:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: New

Development

Successfully merging this pull request may close these issues.

1 participant