Home > database >  Unable to access variable in Jenkins- groovy
Unable to access variable in Jenkins- groovy

Time:10-11

I have the below code in my Jenkins pipeline:

        stage('CR Check') {
         steps{
            script
                {
                    sh """
                        echo "Tagert env is ${targetenv}"
                        if [[ "${targetenv}" == 'preprod' || "${targetenv}" == 'prod' ]]; then 
                            if [[ -z "${CR_NUMBER}" ]]; then
                                echo "ERROR: CR- ${CR_NUMBER} is empty" 
                                exit 1
                            fi
                            echo -n "curl -X GET 'https://xxxxxxx/api/v1/read?changeRequest=" > cr_validate.sh
                            echo -n "${CR_NUMBER}" >> cr_validate.sh
                            echo -n "&format=JSON'  -H 'accept: application/html'"  >> cr_validate.sh
                            cat cr_validate.sh
                            sh cr_validate.sh > cr_validate.json
                            CR_STATUS=`python -c "import json,sys; obj=json.loads(open('cr_validate.json','r').read());print (obj['Status'])"`

                            if [[ "${CR_STATUS}" == "Approved" ]]; then
                                echo 'hi'
                            fi
                        fi
                    """
            }

When I execute the pipeline, I am getting the below error:

hudson.remoting.ProxyException: groovy.lang.MissingPropertyException: No such property: CR_STATUS for class: WorkflowScript
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:66)
....

If I remove the last if else condition where I am using the variable CR_STATUS, the code works and I can also see that a value has been assigned to that variable. But when I try accessing this variable again, I get the same error. I tried every other way of accessing the variable, but it does not work. I don't know what I am doing wrong!

CodePudding user response:

In your case ${CR_STATUS} is being treated as a Jenkins variable and Jenkins is trying to interpolate it. In order to skip this, you can add an escape character before the $. Something like below.

if [[ "\${CR_STATUS}" == "Approved" ]]; then
     echo 'hi'
fi
  • Related