var из разделяемых библиотек, переключитесь на этап Jenkinsfile — нет такого свойства: value1 для класса: groovy.lang.Привязка

#jenkins-pipeline #shared-libraries #jenkins-groovy

#дженкинс-конвейер #разделяемые библиотеки #дженкинс-заводной

Вопрос:

Опять же со старым groovy.lang.MissingPropertyException: нет такого свойства: value1 для класса: groovy.lang.Привязка …

Я продолжаю сталкиваться с этими вещами, на этот раз с разделяемой библиотекой, выполняющей оператор switch.

Есть идеи о том, как считывать переменные (value1, env), которые установлены в библиотеке (которая отлично отображает переменные), в Jenkinsfile (который не получает переменные)?

Я ожидаю: значения jfile — это «some-dev-value» и dev

Jenkinsfile:

 @Library('piplinesharedlib') _
pipeline {
  agent any
    stages {
        stage('env setting by branch') {
            steps {
                branchSelector("${GIT_BRANCH}")
                echo "jfile values are ${value1} and ${env}"
            }
        }
    }
}
  

разделяемая библиотека:

 def call(String GIT_BRANCH) {
    echo "gitbranch is ${GIT_BRANCH}"
    def version = "1.0"

    def values = readProperties file: "${env.WORKSPACE}\values.groovy"
    //def value1 = ''

    switch(GIT_BRANCH) {
        case "develop":
            env = "dev"
            echo "setting env to ${env}"
            value1 = values['DevValueloadedFromReasources']
            break
        case ["master", "Feature*".toString()]:
            env = "prod"
            echo "setting env to ${env}"
            value1 = values['ProdValueloadedFromReasources']
            break
        case "Feature*":
            env = "dev"
            echo "setting env to ${env}"
            value1 = values['FeatureValueloadedFromReasources']
            break
        default:
            value1 = "nothin"
            break
    }
        echo "The values for this env are ${value1} and ${env}"
    }
return this
  

вывод:

 ...
gitbranch is develop
[Pipeline] readProperties
[Pipeline] echo
setting env to dev
[Pipeline] echo
The values for this env are "some-dev-value" and dev
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // withEnv
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
[Bitbucket] Notifying commit build result
[Bitbucket] Build result notified
groovy.lang.MissingPropertyException: No such property: value1 for class: groovy.lang.Binding
    at groovy.lang.Binding.getVariable(Binding.java:63)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:270)
    at org.kohsuke.groovy.sandbox.impl.Checker$6.call(Checker.java:289)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:293)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:269)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:269)
    at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.getProperty(SandboxInvoker.java:29)
    at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:20)
    at WorkflowScript.run(WorkflowScript:32)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.delegateAndExecute(ModelInterpreter.groovy:137)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.executeSingleStage(ModelInterpreter.groovy:682)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.catchRequiredContextForNode(ModelInterpreter.groovy:417)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.catchRequiredContextForNode(ModelInterpreter.groovy:415)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.executeSingleStage(ModelInterpreter.groovy:681)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.evaluateStage(ModelInterpreter.groovy:280)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.toolsBlock(ModelInterpreter.groovy:566)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.toolsBlock(ModelInterpreter.groovy:565)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.evaluateStage(ModelInterpreter.groovy:270)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.withEnvBlock(ModelInterpreter.groovy:465)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.withEnvBlock(ModelInterpreter.groovy:464)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.evaluateStage(ModelInterpreter.groovy:269)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.withCredentialsBlock(ModelInterpreter.groovy:503)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.withCredentialsBlock(ModelInterpreter.groovy:502)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.evaluateStage(ModelInterpreter.groovy:268)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.evaluateStage(ModelInterpreter.groovy:315)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.inDeclarativeAgent(ModelInterpreter.groovy:607)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.inDeclarativeAgent(ModelInterpreter.groovy:606)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.evaluateStage(ModelInterpreter.groovy:312)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.stageInput(ModelInterpreter.groovy:378)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.stageInput(ModelInterpreter.groovy:377)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.evaluateStage(ModelInterpreter.groovy:311)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.inWrappers(ModelInterpreter.groovy:634)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.inWrappers(ModelInterpreter.groovy:633)
    at org.jenkinsci.plugins.pipeline.modeldefinition.ModelInterpreter.evaluateStage(ModelInterpreter.groovy:251)
    at ___cps.transform___(Native Method)
    at com.cloudbees.groovy.cps.impl.PropertyishBlock$ContinuationImpl.get(PropertyishBlock.java:74)
    at com.cloudbees.groovy.cps.LValueBlock$GetAdapter.receive(LValueBlock.java:30)
    at com.cloudbees.groovy.cps.impl.PropertyishBlock$ContinuationImpl.fixName(PropertyishBlock.java:66)
    at sun.reflect.GeneratedMethodAccessor378.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
    at com.cloudbees.groovy.cps.impl.ConstantBlock.eval(ConstantBlock.java:21)
    at com.cloudbees.groovy.cps.Next.step(Next.java:83)
    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:174)
    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:163)
    at org.codehaus.groovy.runtime.GroovyCategorySupport$ThreadCategoryInfo.use(GroovyCategorySupport.java:129)
    at org.codehaus.groovy.runtime.GroovyCategorySupport.use(GroovyCategorySupport.java:268)
    at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:163)
    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.access$001(SandboxContinuable.java:18)
    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.run0(SandboxContinuable.java:51)
    at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:186)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:370)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$200(CpsThreadGroup.java:93)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:282)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:270)
    at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:64)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:131)
    at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
    at jenkins.security.ImpersonatingExecutorService$1.run(ImpersonatingExecutorService.java:59)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Finished: FAILURE
  

Ответ №1:

Попробуйте использовать глобальный:

 def value1 = null // or maybe simply `value1 = null` if this doesn't work

@Library('piplinesharedlib') _

pipeline {
  

Ответ №2:

чтобы решить вашу проблему, сначала создайте файл groovy с именем SharedLib.groovy и определите две глобальные переменные «value1» и «env», затем аннотируйте их с помощью @Field со значением по умолчанию. измените значение этих двух переменных в вашем методе.

 #!/usr/bin/env groovy

import groovy.transform.Field

@Field value1 = ''
@Field env = ''
def myMethod(String GIT_BRANCH) {
    echo "gitbranch is ${GIT_BRANCH}"
    def version = "1.0"

    //def values = readProperties file: "${env.WORKSPACE}\values.groovy"

    //def value1 = ''

    switch(GIT_BRANCH) {
        case "develop":
            env = "dev"
            echo "setting env to ${env}"
            value1 ="1"
            break
        case ["master", "Feature*".toString()]:
            env = "prod"
            echo "setting env to ${env}"
            value1 ="2"
            break
        case "Feature*":
            env = "dev"
            echo "setting env to ${env}"
            value1 = "3"
            break
        default:
            value1 = "nothin"
            break
    }
        echo "The values for this env are ${value1} and ${env}"
    }
  

затем используйте следующий код

 @Library("piplinesharedlib") _
pipeline {
  agent {label "coreop-pasargad-246"}
    stages {
        stage('env setting by branch') {
            steps {
            script{
                sharedLib.myMethod("${GIT_BRANCH}");

                //branchSelector("${GIT_BRANCH}")
                echo "jfile values are ${sharedLib.value1} and ${sharedLib.env}"
            }
            }
        }
    }
}   
  

Ответ №3:

Бьюсь головой о стену … как оказалось, работает простой вызов ${branchSelector.value1}.

     stage('env setting by branch') {
        steps {
            branchSelector("${GIT_BRANCH}")
            echo "jfile values are ${branchSelector.value1} and ${branchSelector.env}"
        }
    }