'groovy jenkinsfile to read a json file before `step` starts

I'm using Jenkins, we want to read a json file to provide necessary details within the jenkins scripts such as IP as an example.

Jenkinsfile

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

Error facing is

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)


Solution 1:[1]

Declaring the variable outside the pipeline and initializing it in a script section within the stage where it is needed should work. The pipeline might look something like below:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1