From 3f601ff7b54cb5a7d4ddf5fe98e06b77a27dcdcc Mon Sep 17 00:00:00 2001 From: Virgil Date: Fri, 3 Apr 2026 13:43:15 +0000 Subject: [PATCH] feat(ansible): expose play magic vars --- executor.go | 4 ++++ executor_extra_test.go | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/executor.go b/executor.go index 5c041de..149294e 100644 --- a/executor.go +++ b/executor.go @@ -439,6 +439,8 @@ func (e *Executor) runPlay(ctx context.Context, play *Play) error { return nil // No hosts matched } e.endedHosts = make(map[string]bool) + e.vars["ansible_play_hosts_all"] = append([]string(nil), hosts...) + e.vars["ansible_play_hosts"] = append([]string(nil), hosts...) // Merge play vars if err := e.loadPlayVarsFiles(play); err != nil { @@ -457,6 +459,8 @@ func (e *Executor) runPlay(ctx context.Context, play *Play) error { if len(batch) == 0 { continue } + e.vars["ansible_play_hosts"] = append([]string(nil), e.filterActiveHosts(hosts)...) + e.vars["ansible_play_batch"] = append([]string(nil), batch...) e.batchFailedHosts = make(map[string]bool) runSection := func(fn func() error) error { if err := fn(); err != nil { diff --git a/executor_extra_test.go b/executor_extra_test.go index b646083..8cfd1b9 100644 --- a/executor_extra_test.go +++ b/executor_extra_test.go @@ -775,6 +775,44 @@ func TestExecutorExtra_SplitSerialHosts_Good_ListRepeatsLastValue(t *testing.T) assert.Equal(t, []string{"host5"}, batches[3]) } +func TestExecutorExtra_RunPlay_Good_ExposesPlayMagicVars(t *testing.T) { + e := NewExecutor("/tmp") + gatherFacts := false + e.SetInventoryDirect(&Inventory{ + All: &InventoryGroup{ + Hosts: map[string]*Host{ + "host1": {}, + "host2": {}, + }, + }, + }) + e.clients["host1"] = NewMockSSHClient() + e.clients["host2"] = NewMockSSHClient() + + play := &Play{ + Hosts: "all", + Serial: 1, + GatherFacts: &gatherFacts, + Tasks: []Task{ + { + Name: "Inspect play magic vars", + Module: "debug", + Args: map[string]any{ + "msg": "{{ ansible_play_hosts_all }}|{{ ansible_play_hosts }}|{{ ansible_play_batch }}", + }, + Register: "magic_vars", + }, + }, + } + + require.NoError(t, e.runPlay(context.Background(), play)) + + require.NotNil(t, e.results["host1"]["magic_vars"]) + assert.Equal(t, "[host1 host2]|[host1 host2]|[host1]", e.results["host1"]["magic_vars"].Msg) + require.NotNil(t, e.results["host2"]["magic_vars"]) + assert.Equal(t, "[host1 host2]|[host1 host2]|[host2]", e.results["host2"]["magic_vars"].Msg) +} + // ============================================================ // Tests for handleLookup (0% coverage) // ============================================================