How to dynamically and task to subprojects

In my project I have few very extensive task that I need to set up across multiple sub-projects and want to avoid repetition. So I thought it would make since to somehow define them at the parent level and make them available to the sub-projects from the root gradle file.

In the Multi project build doc it talks about the different options for modifying existing.

My question is how do I dynamically add task for certain sub-projects from the parent project. I am trying the following, but the output is not what I was expecting.

def subProjectsOfInterest(){return [:project1 :project2]}
configure(subProjectsOfInterest()){
  task dummyTask { println "project: ${project.name}"}
}

When I run this I get:
./gradlew :project1:dummyTask
project: project1
project: project2

It looks like dummyTask was ran for all projects of interest, I was only expecting it to run for project1. What am I doing wrong? Is there a better way?

I know Im missing some :fearful:

What is in the closure is the task configuration, so you are right the tasks are configured for both projects as Gradle instantiates the whole task graph before it starts looking at what to run (search for “config on demand” if you want to change that)

What you are missing here is doLast { ... }, which is how you specify a custom action.