如何在 Jenkinsfile 声明性管道中动态更改阶段名称?

时间:2021-06-25 19:05:00

标签: jenkins jenkins-pipeline jenkins-groovy jenkins-job-dsl jenkins-declarative-pipeline

我有 Jenkinsfile(脚本化流水线)

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}";
    }
}

想转换为声明式之后

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}";
            }
        }

    }
}

启动Jenkins Job后停止并返回错误

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}") {
                     ^

尝试使用

stage('run template ${template1}')

还有其他

stage('run template '+template1)

也返回错误。

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您可以使用如下顺序阶段创建动态阶段:

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