feat(ansible): honour include task conditions

Co-Authored-By: Virgil <virgil@lethean.io>
This commit is contained in:
Virgil 2026-04-02 13:38:45 +00:00
parent 1b633d41db
commit bced0d3cdc
2 changed files with 48 additions and 0 deletions

View file

@ -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)

View file

@ -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(`---