AminSojoudi
AminSojoudi

Reputation: 2016

setting environment variables in jenkins file

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

Upvotes: 0

Views: 5044

Answers (2)

AminSojoudi
AminSojoudi

Reputation: 2016

Just found another way to use defined environment variables.

def getsomeVariable (){
    return 'foo'
}


pipeline{
    agent any

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

}

Upvotes: 0

lvthillo
lvthillo

Reputation: 30811

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

Upvotes: 3

Related Questions