Include queried facts as host vars in -A inventory
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful

`-A` emitted hosts with empty vars, so `-F ipaddress,enc_role -A` lost the facts
it just queried. Ansible inventories are far more useful with the values inline.

- Extract factsByHost() (the {host: {fact: value}} builder) and share it between
  -j and -A so the Ansible inventory attaches each host's queried fact(s) as
  host vars, keyed by real fact name.
- Strengthen the Ansible test to assert host vars and add a multi-fact case.
This commit is contained in:
2026-07-05 17:39:53 +10:00
parent 103ebb2393
commit 5d0f69483b
3 changed files with 65 additions and 26 deletions
+33
View File
@@ -9,6 +9,8 @@ import (
"path/filepath"
"strings"
"testing"
"gopkg.in/yaml.v3"
)
// ---- helpers ----------------------------------------------------------------
@@ -772,6 +774,37 @@ func TestRun_Ansible(t *testing.T) {
if !strings.Contains(out, "hosta:") || !strings.Contains(out, "hostb:") {
t.Fatalf("expected both hosts in inventory, got: %q", out)
}
// The queried fact is attached as a host var.
if !strings.Contains(out, "enc_role: roles::db") || !strings.Contains(out, "enc_role: roles::web") {
t.Fatalf("expected fact host vars in inventory, got: %q", out)
}
}
func TestRun_Ansible_MultipleFacts(t *testing.T) {
// -F ipaddress,enc_role -A must include both facts as host vars.
facts := []fact{
{Certname: "hosta", Name: "ipaddress", Value: rawJSON("198.18.0.1")},
{Certname: "hosta", Name: "enc_role", Value: rawJSON("roles::dns")},
}
out := runToString(t, facts, func(a *runArgs) {
a.showRole = false
a.factName = "ipaddress,enc_role"
a.ansible = true
})
// Parse it back as YAML and assert the structure precisely.
var inv struct {
All struct {
Hosts map[string]map[string]interface{} `yaml:"hosts"`
} `yaml:"all"`
}
if err := yaml.Unmarshal([]byte(out), &inv); err != nil {
t.Fatalf("inventory is not valid YAML: %v (%s)", err, out)
}
host := inv.All.Hosts["hosta"]
if host["ipaddress"] != "198.18.0.1" || host["enc_role"] != "roles::dns" {
t.Fatalf("expected both facts as host vars, got: %v", host)
}
}
func TestRun_AllFacts_PrintsSortedByName(t *testing.T) {