Run a task from an other plugin

I would like to execute inside my task (in my own plugin) a task from a other plugin. Before the cyclone task is executed i need to set some configuration settings. The problem is that the cyclone task is not executed. Any hints what wrong?

public class MyTask extends DefaultTask {

  @TaskAction
  public void perform()  {
    CycloneDxTask task = (CycloneDxTask) getProject().getTasks().getByName("cyclonedx");
    task.setIncludeConfigs(List.of("runtimeClasspath"));
    task.setSkipConfigs(List.of("compileClasspath", "testCompileClasspath"));

    task.doLast(task1 -> {
      getProject().getLogger().info("doLast:  " + task1.getDescription());
    });
  }
}

You cannot “invoke” tasks, you can only depend on them.
And you shouldn’t configure tasks from the execution phase, even other tasks.
At least that is then incompatible with the configuration cache.

If you really want to do it, you should make the cyclonedx task depensOn your custom task that configures it, so that if the cyclonedx task is run, your task is run first and can configure it.
If you want the cyclonedx task to always run when your custom task was run you can also add additionally a finalizedBy from your task to cyclonedx.

But again, this is not compatible with configuration cache, so should better be avoided.

hmm, what would be a proper solution? i have to set the same settings for this plugin on several services and would like to do it only once.

I found an otherway that seems to work. Would this be more appropriate? In that case i try to set the settings directly on the orignial task.

...
  public void apply(Project project) {
    CycloneDxTask task = (CycloneDxTask) project.getTasks().getByName("cyclonedx")
    task.setIncludeConfigs(List.of("runtimeClasspath"));
    task.setSkipConfigs(List.of("compileClasspath", "testCompileClasspath"));
...

Almost, by using getByName, you circumvent task-configuration avoidance.

It is better to do it in a lazy manner.

For that you have basically two options in your convention plugin.

Either you say “whenever my convention plugin is applied, the cyclone dx plugin also needs to be applied and configured”, then you want something like:

project.apply(Map.of("plugin", "org.cyclonedx.bom"));
project.getTasks().named("cyclonedx", CycloneDxTask.class, task -> {
    task.setIncludeConfigs(List.of("runtimeClasspath"));
    task.setSkipConfigs(List.of("compileClasspath", "testCompileClasspath"));
});

Or you say “if the cyclone dx plugin is applied, then configure its task”, then you want something like:

project.getPluginManager().withPlugin("org.cyclonedx.bom", __ ->
        project.getTasks().named("cyclonedx", CycloneDxTask.class, task -> {
            task.setIncludeConfigs(List.of("runtimeClasspath"));
            task.setSkipConfigs(List.of("compileClasspath", "testCompileClasspath"));
        }));

Thanks for your answer. that worked.