0

I am trying to write a jenkins build script for my project in Groovy. the problem is that I want to define some variables at the top of the script and use them when I want as Environment variable.

def someVariable = 'foo'

pipeline{
    agent any

    stages{
        stage("build"){
            environment {
                specialParameter = someVariable
            }
            steps{
                ...
            }
        }
        ...
    }

}

I have some other steps that their environment variables are different and also I want to just change the top of the script to able to build other branches and so on. so I just want a way to use the defined someVariable in the environment body.

Thanks

2 Answers 2

3

First you can just use the environment section to define environment variables which are known in you whole script:

pipeline {
    agent any
    environment {
        TEST='myvalue'
    }
    stages{
        stage("build"){
            steps{
                ...
            }
        }
    }
}

You can also define a variable which is only known in one stage:

pipeline {
    agent any
    stages{
        stage("build"){
            environment {
                TEST='myvalue'
            }
            steps{
                ...
            }
        }
    }
}

But for your solution (using def above the pipeline) you can just do:

def someVariable = 'foo'

pipeline{
    agent any

    stages{
        stage("build"){
            steps{
                echo someVariable
            }
        }
    }
}

This will output 'foo'.

You can get more informations on variable declarations syntax by reading Jenkins online book.

UPDATE:

def someVariable = 'foo'

pipeline{
    agent any

    stages{
        stage("build"){
            environment {
                TEST = sh(script: "echo -n ${someVariable}", returnStdout: true)
            }
            steps{
                sh 'echo "${TEST}"'
            }
        }
    }
}

Output:

[test] Running shell script
+ echo foo
foo
Sign up to request clarification or add additional context in comments.

1 Comment

maybe my question is ambiguous, I think you did not pay enough attention to my question, last sentence of my question specifies what I want. I want to use declared variable inside "environment body" not in "steps", just look at my code.
0

Just found another way to use defined environment variables.

def getsomeVariable (){
    return 'foo'
}


pipeline{
    agent any

    stages{
        stage("build"){
            environment {
                specialParameter = getsomeVariable()
            }
            steps{
                ...
            }
        }
        ...
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.