【问题标题】:How make dynamic change stage name in Jenkinsfile Declarative pipeline?如何在 Jenkinsfile 声明式管道中动态更改阶段名称?
【发布时间】:2021-06-25 19:05:00
【问题描述】:

我有 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)

也返回错误。

如何解决这个问题?

【问题讨论】:

  • 错误信息暗示你不能这样做。

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


【解决方案1】:

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

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

【讨论】:

  • @Nikolay Baranenko 为您完成这项工作
  • stage('Dynamic Stages') - 解决方案上下文阶段可能为空?
  • 是的,您可以,但在显示时会显示 error 而不是 Dynamic stages
猜你喜欢
  • 2022-10-27
  • 1970-01-01
  • 1970-01-01
  • 2023-03-21
  • 2021-08-02
  • 1970-01-01
  • 1970-01-01
  • 2020-05-29
  • 2018-08-21
相关资源
最近更新 更多