初始分支创建时未在jenkins服务器中配置jenkinsfile参数属性

nhjlsmyf  于 2023-04-29  发布在  Jenkins
关注(0)|答案(5)|浏览(127)

我已经用下面的属性配置了jenkinsfile,但是当从master分支创建一个新分支时,它不适用于jenkins服务器。

#!groovy

properties([[$class: 'ParametersDefinitionProperty',
    parameterDefinitions: [
        [$class: 'StringParameterDefinition', name: 'isValid', defaultValue: 'false']
    ]
]])

node {
    stage 'Checkout'        
        checkout scm
    .....
    .....
}

在git中创建分支后,该分支在jenkins服务器中可见,并带有立即构建选项。
第一次从jenkins服务器上运行分支后,会变成Build with Parameters选项。
我在jenkinsfile中有没有遗漏什么需要配置的?为什么在创建分支时没有在jenkins服务器中配置参数?

w8ntj3qf

w8ntj3qf1#

您可以通过使用params.isValid而不是env.isValid来解决这个问题。

wlp8pajw

wlp8pajw2#

我用来解决这个问题的方法是检查分支上的env.BUILD_NUMBER == "1",然后为我的参数设置一些默认值,以便在该分支的初始运行中使用。例如:

node {
  properties([
    buildDiscarder(logRotator(artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '15')),
    parameters([
      string(defaultValue: '', description: '', name: 'PLATFORM')
    ])
  ])

  stage("Testing") {
    // set a default for PLATFORM if it's the first build of a PR
    // as a workaround to parameters not being available on first run of build
    if (env.BUILD_NUMBER == "1") {
      PLATFORM = ''
    }

    if (PLATFORM.empty) {
      ....
    }
  }
}
myzjeezk

myzjeezk3#

这似乎在2019年被打破。您可以通过在管道中设置一个初始阶段来解决这个问题,该阶段将参数值设置回环境变量。之后,您可以在后续阶段正常引用它。

parameters {
    string(name: 'SOME_VAR', defaultValue: 'foo', description: 'A custom environment variable')
}

....

stage('Verifying Environment Variables') {
    // This is too work around a jenkins bug on the first build of a multi-branch job
    // https://issues.jenkins-ci.org/browse/JENKINS-40574 - it is marked resolved but the last comment says it doesn't work for declaritive pipelines
    environment {
        SOME_VAR = "${params.SOME_VAR}"
    }
    steps {
        script {
            env.SOME_VAR = env.SOME_VAR
        }
    }
}
...
qpgpyjmq

qpgpyjmq4#

如果你使用的是声明式管道,只需添加下面的阶段作为你的第一阶段。

stage('Preparations') {
  steps {
    echo 'Initialize parameters as environment variables due to https://issues.jenkins-ci.org/browse/JENKINS-41929'
    evaluate """${def script = ""; params.each { k, v -> script += "env.${k} = \"${v}\"\n" }; return script}"""
  }
}

此问题在JENKINS-41929上被跟踪。

fgw7neuy

fgw7neuy5#

管道脚本中的首次属性初始化存在类似问题。看起来最好的方法是这样的,例如我有SKIP_RUN参数,当我更新作业管道时,我可以在每个管道中运行它,并且在Jenkins UI中更新属性:

**注意:**这里的主要内容是,如果property为'null',则给出初始值“def skipRun = params。SKIP_RUN?:true”

properties([
    parameters([
        booleanParam(name: 'SKIP_RUN', description: 'Skips all stages. Used to update parameters in case of changes.', defaultValue: false),
    ])
])

pipeline {
    agent any
    stages {
        stage('skip run') {
            steps {
                script {
                    // First time when added 'params.SKIP_RUN' will be null, setting value to true when 'SKIP_RUN' is not eat initialized to skip build.
                    def skipRun = params.SKIP_RUN ?: true
                    echo "SKIP_RUN: '${skipRun}';"
                    if(skipRun) {
                        currentBuild.description = "SKIPPED"
                        currentBuild.result = 'ABORTED'
                        error("Aborting the build - SKIP_RUN is set to true")
                    }
                }
            }
        }
        stage("Do job stage") {
           //...
       }
   }

}

更新时间:2023-04-25(脚本v2 -改进版)。不知道为什么,但最初的答案(上面的脚本块)开始不工作-像往常一样,SKIP_RUN开始为空。因此,这里是“SKIP_BUILD”属性的改进答案,我使用它来跳过构建所有作业以初始化Jenkins作业参数更改。脚本检查null属性,也检查在以前的构建中是否存在此属性-如果不存在,则意味着我们需要SKIP_RUN并初始化属性:

properties([
        parameters([
            booleanParam(name: 'SKIP_RUN', description: 'Skips all stages. Used to update parameters in case of changes.', defaultValue: false)
        ])
    ])
    
pipeline {
    agent any
    stages {
        stage('skip run') {
            steps {
                script {
                    try {
                        // Set skipRun to true only if SKIP_RUN is not initialized, the pipeline is not running for the first time, and the previous build did not have SKIP_RUN set to true.
                        echo "SKIP_RUN: '${params.SKIP_RUN}';"
                        echo "previousBuild: '${currentBuild.rawBuild.previousBuild}';"
        
                        def noSkipParamInPreviousBuild = false
                        if (currentBuild?.rawBuild?.previousBuild?.actions != null) {
                            noSkipParamInPreviousBuild = !currentBuild.rawBuild.previousBuild.getAction(ParametersAction.class)?.getParameter("SKIP_RUN")
                        }
                        echo "noSkipParamInPreviousBuild: '${noSkipParamInPreviousBuild}';"
        
                        def skipRun = currentBuild.rawBuild.previousBuild == null || (params.SKIP_RUN == null && noSkipParamInPreviousBuild) || params.SKIP_RUN == true
                        echo "skipRun: ${skipRun}';"
        
                        if(skipRun) {
                            currentBuild.description = "SKIPPED"
                            currentBuild.result = 'ABORTED'
                            error("Aborting the build - SKIP_RUN is set to ${skipRun}")
                        }
                    } catch (Exception e) {
                        echo "Exception message: ${e.getMessage()}"
                        throw e
                    }
                }
            }
        }
        stage("Do job stage") {
            //...
        }
    }

}

**注意:**您需要批准一些类/方法/脚本在Jenkins中执行。

相关问题