From bced0d3cdcff4d8ad7c233f4c3fc60025c0deefd Mon Sep 17 00:00:00 2001 From: Virgil Date: Thu, 2 Apr 2026 13:38:45 +0000 Subject: [PATCH] feat(ansible): honour include task conditions Co-Authored-By: Virgil --- executor.go | 15 +++++++++++++++ executor_extra_test.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/executor.go b/executor.go index 93e15c3..aeb623d 100644 --- a/executor.go +++ b/executor.go @@ -1704,6 +1704,21 @@ func (e *Executor) runIncludeTasks(ctx context.Context, hosts []string, task *Ta return nil } + // Static include/import tasks still honour their own when-clause before the + // child task file is expanded for each host. + if task.When != nil { + filtered := make([]string, 0, len(hosts)) + for _, host := range hosts { + if e.evaluateWhen(task.When, host, task) { + filtered = append(filtered, host) + } + } + hosts = filtered + if len(hosts) == 0 { + return nil + } + } + // Resolve the include path per host so host-specific vars can select a // different task file for each target. hostsByPath := make(map[string][]string) diff --git a/executor_extra_test.go b/executor_extra_test.go index 4b95819..9996f8c 100644 --- a/executor_extra_test.go +++ b/executor_extra_test.go @@ -833,6 +833,39 @@ func TestExecutorExtra_RunIncludeTasks_Good_HostSpecificTemplate(t *testing.T) { assert.Contains(t, started, "db1:DB included task") } +func TestExecutorExtra_RunIncludeTasks_Good_HonoursWhen(t *testing.T) { + dir := t.TempDir() + includedPath := joinPath(dir, "conditional.yml") + yaml := `- name: Conditional included task + debug: + msg: should not run +` + require.NoError(t, writeTestFile(includedPath, []byte(yaml), 0644)) + + gatherFacts := false + play := &Play{ + Name: "Conditional include", + Hosts: "localhost", + GatherFacts: &gatherFacts, + } + + e := NewExecutor(dir) + e.SetVar("include_enabled", false) + + var started []string + e.OnTaskStart = func(host string, task *Task) { + started = append(started, host+":"+task.Name) + } + + require.NoError(t, e.runTaskOnHosts(context.Background(), []string{"localhost"}, &Task{ + Name: "Load conditional tasks", + IncludeTasks: "conditional.yml", + When: "include_enabled", + }, play)) + + assert.Empty(t, started) +} + func TestExecutorExtra_RunIncludeRole_Good_InheritsTaskVars(t *testing.T) { dir := t.TempDir() require.NoError(t, writeTestFile(joinPath(dir, "roles", "demo", "tasks", "main.yml"), []byte(`---