Search code examples
jenkinsjenkins-pipelinejenkins-groovyjenkins-job-dsljenkins-declarative-pipeline

How make dynamic change stage name in Jenkinsfile Declarative pipeline?


I have Jenkinsfile (Scripted Pipeline)

def template1 = "spread_sshkeys"

node {
    // Clean before build
    stage('Checkout') {
        deleteDir()
        checkout scm
        sh "git submodule foreach --recursive git pull origin master";
    }
    stage("import template ${template1}") {
            script{
                sh "ls -las; cd jenkins-ci-examples; ls -las";
                jenkins_ci_examples.sub_module = load "jenkins-ci-examples/${template1}"
            }
    }
    stage("run template ${template1}") {
sh "echo ${jenkins_ci_examples.sub_module}";
    }
}

after want to Converting to Declarative

def template1 = "spread_sshkeys"

pipeline {
    agent any

    stages {
        stage ("Checkout") {
            steps {
                deleteDir()
                checkout scm
                sh "git submodule foreach --recursive git pull origin master"
            }
        }
        stage("import template ${template1}") {
            steps {
                    script {
                        sh "ls -las; cd jenkins-ci-examples; ls -las";
jenkins_ci_examples.sub_module = load "jenkins-ci-examples/${template1}"
                    }
            }
        }
        stage("run template ${template1}") {
            steps {
                sh "echo ${jenkins_ci_examples.sub_module}";
            }
        }

    }
}

After start Jenkins Job stop and return Error

WorkflowScript: 22: Expected string literal @ line 22, column 19.
               stage("import template ${template1}") {
                     ^

WorkflowScript: 30: Expected string literal @ line 30, column 19.
               stage("run template ${template1}") {
                     ^

Try to use

stage('run template ${template1}')

and else

stage('run template '+template1)

returned error too.

How solve this problem?


Solution

  • You can create dynamic stages using sequential stages as below:

    def template1 ="spread_sshkeys"
    pipeline {
        agent any
    
        stages {
            stage('Dynamic Stages') {
                
                steps {
                    script {
                            stage("import template ${template1}"){
                                println("${env.STAGE_NAME}")
                            }
                             stage("run template ${template1}"){
                                println("${env.STAGE_NAME}")
                            }
                    }
                }
            }
            
        }
    }
    
    

    enter image description here