# Create stage dynamically in declarative pipeline

```groovy
// in a declarative pipeline
stage('Trigger Building') {
  when {
    environment(name: 'DO_BUILD_PACKAGES', value: 'true')
  }
  steps {
    executeModuleScripts('build') // local method, see at the end of this script
  }
}


// at the end of the file or in a shared library
void executeModuleScripts(String operation) {

  def allModules = ['module1', 'module2', 'module3', 'module4', 'module11']

  allModules.each { module ->
    String action = "${operation}:${module}"
  
    echo("---- ${action.toUpperCase()} ----")
    String command = "npm run ${action} -ddd"
  
    // here is the trick
    script {
      stage(module) {
        bat(command)
      }
    }
  }
}
```

### References

* <https://stackoverflow.com/questions/42837066/can-i-create-dynamically-stages-in-a-jenkins-pipeline>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ryanzzff.gitbook.io/til/jenkins/create-stage-dynamically-in-declarative-pipeline.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
