8

I know I can have an environment section on jenkins pipeline (declarative) for a stage. Like this:

stage('Name') {
    environment {
        NAME = value
    }   
    steps {
        script {
            Do something using these env vars
        }
    }
} 

I want to write a groovy function, to define some env vars, and run something, and call it from a few pipelines. Something like:

def function () {
    environment {
        NAME = value
    }
    sh "do something using these env vars"
}

Is it possible somehow?

(I know I can write sh "ENV=value; some CMD" but I have few variables, and it is less read-able).

Matthew Schuchard
  • 25,172
  • 3
  • 47
  • 67
hagits
  • 359
  • 1
  • 3
  • 8

1 Answers1

15

Yes, you can do this. Jenkins Pipeline stores its environment variables in a map named ENV. Therefore, you can add additional key value pairs to this map for additional environment variables. This would be done in Groovy syntax via:

// syntax option one
env.key = value
// syntax option two
env['key'] = value

For your example, this would look like:

def function () {
  env.NAME = value
  sh "do something using these env vars"
}
hagits
  • 359
  • 1
  • 3
  • 8
Matthew Schuchard
  • 25,172
  • 3
  • 47
  • 67