groovy jenkinsfile在'step'开始前读取一个json文件

nwo49xxi  于 2022-11-01  发布在  Jenkins
关注(0)|答案(1)|浏览(311)

我正在使用Jenkins,我们希望读取一个json文件,以在jenkins脚本中提供必要的详细信息,例如IP。
Jenkins锉

def getSecrets(json_file_path, env, var){
  def inputFile = new File(json_file_path)
  def InputJSON = new JsonSlurper().parse(inputFile)
  def secret = InputJSON."${env}"."${var}"
return secret
}
pipeline {
  stages {
    // Below are dev stages
    stage('Dev deployment') {
      environment{
          deployment_env = 'dev'
      }
      def devClusterIP = getSecrets(pwd() + "/values.json", "dev", "IP")
      when {
        expression { GIT_BRANCH_NAME == params.PUBLISH_BRANCH ||  GIT_BRANCH_NAME == params.DEVELOP_BRANCH }
        expression { params.ENV_CHOICE == 'buildOnly' || params.ENV_CHOICE == 'devDeployOnly' }
        beforeInput true
      }

      steps {
       withKubeConfig([credentialsId: 'kubernetes-preproduction-1-cluster', serverUrl: "https://${devClusterIP}"]) {         
         .....
     } 
    }
  }
}

values.json

{
    "dev": {
        "IP": "0.0.0.0"
    }
}

错误面向是

WorkflowScript: 208: Not a valid stage section definition: "def devIP = getSecrets(pwd() + "/values.json", "dev", "IP")". Some extra configuration is required. @ line 208, column 5.

       stage('Dev deployment') {

       ^

1 error

    at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)

    at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1085)

    at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:603)
xu3bshqb

xu3bshqb1#

在管道外声明变量并在需要它的阶段内的script节中初始化它应该可以工作。管道可能如下所示:

import groovy.json.JsonSlurper

def getSecrets(jsonFilePath, env, var) {
  return new JsonSlurper().parseText(readFile(jsonFilePath))[env][var]
}

def devClusterIP

pipeline {
  stages {
    // Below are dev stages
    stage('Dev deployment') {
      environment{
        deployment_env = 'dev'
      }
      when {
        expression { GIT_BRANCH_NAME == params.PUBLISH_BRANCH ||  GIT_BRANCH_NAME == params.DEVELOP_BRANCH }
        expression { params.ENV_CHOICE == 'buildOnly' || params.ENV_CHOICE == 'devDeployOnly' }
        beforeInput true
      }

      steps {
        script {
          devClusterIP = getSecrets("values.json", "dev", "IP")
        }
        withKubeConfig([credentialsId: 'kubernetes-preproduction-1-cluster', serverUrl: "https://${devClusterIP}"]) {         

        } 
      }
  }
}

相关问题