code

매개 변수화 된 빌드에서 매개 변수에 액세스하는 방법은 무엇입니까?

codestyles 2020. 12. 14. 08:13
반응형

매개 변수화 된 빌드에서 매개 변수에 액세스하는 방법은 무엇입니까?


parameters"워크 플로"Jenkins 작업의 "이 빌드는 매개 변수화 됨"섹션에 설정된 액세스 방법은 무엇입니까?

테스트 케이스

  1. WORKFLOW 작업을 만듭니다.
  2. "이 빌드는 매개 변수화 됨"을 활성화합니다.
  3. foo기본값으로 STRING PARAMETER 추가 합니다 bar text.
  4. 아래 코드를 다음에 추가하십시오 Workflow Script.

    node()
    {
         print "DEBUG: parameter foo = ${env.foo}"
    }
    
  5. 작업을 실행하십시오.

결과

DEBUG: parameter foo = null


Workflow 플러그인을 사용할 때 env가 아닌 직접 변수를 사용할 수 있다고 생각합니다. 시험:

node()
{
    print "DEBUG: parameter foo = ${foo}"
}

이 스레드에서 몇 가지 솔루션을 시도했습니다. 작동하는 것처럼 보였지만 내 가치는 항상 사실이었고 다음 문제도 발생했습니다 .JENKINS-40235

jenkinsfile다음 구문을 사용하여 groovy에서 매개 변수를 사용했습니다.params.myVariable

다음은 작동하는 예입니다.

해결책

print 'DEBUG: parameter isFoo = ' + params.isFoo
print "DEBUG: parameter isFoo = ${params.isFoo}"

더 자세한 (그리고 작동하는) 예 :

node() {
   // adds job parameters within jenkinsfile
   properties([
     parameters([
       booleanParam(
         defaultValue: false,
         description: 'isFoo should be false',
         name: 'isFoo'
       ),
       booleanParam(
         defaultValue: true,
         description: 'isBar should be true',
         name: 'isBar'
       ),
     ])
   ])

   // test the false value
   print 'DEBUG: parameter isFoo = ' + params.isFoo
   print "DEBUG: parameter isFoo = ${params.isFoo}"
   sh "echo sh isFoo is ${params.isFoo}"
   if (params.isFoo) { print "THIS SHOULD NOT DISPLAY" }

   // test the true value
   print 'DEBUG: parameter isBar = ' + params.isBar
   print "DEBUG: parameter isBar = ${params.isBar}"
   sh "echo sh isBar is ${params.isBar}"
   if (params.isBar) { print "this should display" }
}

산출

[Pipeline] {
[Pipeline] properties
WARNING: The properties step will remove all JobPropertys currently configured in this job, either from the UI or from an earlier properties step.
This includes configuration for discarding old builds, parameters, concurrent builds and build triggers.
WARNING: Removing existing job property 'This project is parameterized'
WARNING: Removing existing job property 'Build triggers'
[Pipeline] echo
DEBUG: parameter isFoo = false
[Pipeline] echo
DEBUG: parameter isFoo = false
[Pipeline] sh
[wegotrade-test-job] Running shell script
+ echo sh isFoo is false
sh isFoo is false
[Pipeline] echo
DEBUG: parameter isBar = true
[Pipeline] echo
DEBUG: parameter isBar = true
[Pipeline] sh
[wegotrade-test-job] Running shell script
+ echo sh isBar is true
sh isBar is true
[Pipeline] echo
this should display
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

"동일한 이름의 Groovy 변수로 액세스 할 수 있습니다."라는 잘못된 파이프 라인 tutorial # build-parameters 인용문 을 업데이트하기 위해 Pull Request보냈습니다 . . ;)

편집 : Jesse Glick이 지적했듯이 : 릴리스 노트 는 더 자세한 내용으로 이동합니다.

또한 파이프 라인 작업 플러그인을 2.7 이상으로 업데이트하여 빌드 매개 변수가 환경 변수로 정의되어 마치 전역 Groovy 변수 인 것처럼 액세스 할 수 있도록해야합니다.


빌드 매개 변수 인 foo를 추가하면 "베어 변수"처럼 작동하는 것으로 변환되므로 스크립트에서 다음을 수행합니다.

node {
   echo foo
}

워크 플로 스크립트의 구현을 보면 스크립트가 실행될 때 WorkflowScript라는 클래스가 동적으로 생성되는 것을 볼 수 있습니다. 스크립트의 모든 문은이 클래스의 컨텍스트에서 실행됩니다. 이 스크립트로 전달 된 모든 빌드 매개 변수는이 클래스에서 액세스 할 수있는 속성으로 변환됩니다.

예를 들어 다음을 수행 할 수 있습니다.

node {
    getProperty("foo")
}

궁금하다면 WorkflowScript 클래스의 빌드 매개 변수, 환경 변수 및 메서드를 인쇄하기 위해 작성한 워크 플로 스크립트가 있습니다.

node {
   echo "I am a "+getClass().getName()

   echo "PARAMETERS"
   echo "=========="
   echo getBinding().getVariables().getClass().getName()
   def myvariables = getBinding().getVariables()
   for (v in myvariables) {
       echo "${v} " + myvariables.get(v)
   }
   echo STRING_PARAM1.getClass().getName()

   echo "METHODS"
   echo "======="
   def methods = getMetaClass().getMethods()

   for (method in methods) {
       echo method.getName()    
   } 

   echo "PROPERTIES"
   echo "=========="
   properties.each{ k, v -> 
       println "${k} ${v}" 
   }
   echo properties
   echo properties["class"].getName()

   echo "ENVIRONMENT VARIABLES"
   echo "======================"
   echo "env is " + env.getClass().getName()
   def envvars = env.getEnvironment()
   envvars.each{ k, v ->
        println "${k} ${v}"
   }
}

다음은 빌드 매개 변수가 설정되었는지 여부를 테스트하기 위해 시도한 또 다른 코드 예제입니다.

node {
   groovy.lang.Binding myBinding = getBinding()
   boolean mybool = myBinding.hasVariable("STRING_PARAM1")
   echo mybool.toString()
   if (mybool) {
       echo STRING_PARAM1
       echo getProperty("STRING_PARAM1")
   } else {
       echo "STRING_PARAM1 is not defined"
   }

   mybool = myBinding.hasVariable("DID_NOT_DEFINE_THIS")
   if (mybool) {
       echo DID_NOT_DEFINE_THIS
       echo getProperty("DID_NOT_DEFINE_THIS")
   } else {
       echo "DID_NOT_DEFINE_THIS is not defined"
   }
}

매개 변수 변수에 접두사 "params"를 추가합니다. 예를 들면 :

params.myParam

잊지 마세요 : myParam의 일부 방법을 사용하는 경우 "스크립트 승인"에서 승인해야 할 수 있습니다.


작은 따옴표 대신 큰 따옴표 사용

e.g. echo "$foo" as opposed to echo '$foo'

If you configured your pipeline to accept parameters using the Build with Parameters option, those parameters are accessible as Groovy variables of the same name. See Here.

You can drop the semicolon (;), drop the parentheses (( and )), and use single quotes (') instead of double (") if you do not need to perform variable substitutions. See Here. This clued me into my problem, though I've found that only the double (") is required to make it work.


The following snippet gives you access to all Job params

    def myparams = currentBuild.rawBuild.getAction(ParametersAction)
    for( p in myparams ) {
        pMap[p.name.toString()] = p.value.toString()
    }

Please note, the way that build parameters are accessed inside pipeline scripts (pipeline plugin) has changed. This approach:

getBinding().hasVariable("MY_PARAM")

Is not working anymore. Please try this instead:

def myBool = env.getEnvironment().containsKey("MY_BOOL") ? Boolean.parseBoolean("$env.MY_BOOL") : false

Hope the following piece of code works for you:

def item = hudson.model.Hudson.instance.getItem('MyJob')

def value = item.lastBuild.getEnvironment(null).get('foo')

As per Pipeline plugin tutorial:

If you have configured your pipeline to accept parameters when it is built — Build with Parameters — they are accessible as Groovy variables of the same name.

So try to access the variable directly, e.g.:

node()
{
     print "DEBUG: parameter foo = " + foo
     print "DEBUG: parameter bar = ${bar}"
}

You can also try using parameters directive for making your build parameterized and accessing parameters:

Doc: Pipeline syntax: Parameters

Example:

pipeline{

agent { node { label 'test' } }
options { skipDefaultCheckout() }

parameters {
    string(name: 'suiteFile', defaultValue: '', description: 'Suite File')
}
stages{

    stage('Initialize'){

        steps{

          echo "${params.suiteFile}"

        }
    }
 }

참고URL : https://stackoverflow.com/questions/28572080/how-to-access-parameters-in-a-parameterized-build

반응형