Declarative pipeline - options and variable environment

54 views
Skip to first unread message

Côme Trésarrieu

unread,
Feb 16, 2017, 9:16:43 AM2/16/17
to Jenkins Users
Hi all,

I am using withCredentials in pretty much every one of my stages and I would like to know if there is a way to only call it once.
I found a topic [JENKINS-37823] mentionning the wrapper section (now deprecated in favor of the options directive) but options does not recognize withCredentials as a valid type.

I also would like to know if the environment directives as any way of defining environment variables depending on a condition (move the start of the script inside the environment pipeline directive).

Here is a simplified version of my pipeline script.

```
#!groovy

env.VAR1='value1'
env.VAR2='value2'

if (platform ==~ /.*production-srv.*/) {
  env.VAR1='valueA'
  env.VAR2='valueB'
}

pipeline {
  environment {
    // Can't use this
  }

  parameters {
    // some params
  }

  options {
    buildDiscarder(logRotator(numToKeepStr:'10'))
  }

  agent {
    label 'master'
  }

  stages {

    stage('init') {
      steps {
        // blabla
      }
    }

    stage('Step 2') {
      steps {
        withCredentials([[$class          : 'UsernamePasswordMultiBinding', credentialsId: id,
                          usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
          // Do first work
        }
      }
    }

    stage('Step 3') {
        withCredentials([[$class          : 'UsernamePasswordMultiBinding', credentialsId: id,
                          usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
          // Second part
        }
      }
    }
   
    stage('Step 4') {
        withCredentials([[$class          : 'UsernamePasswordMultiBinding', credentialsId: id,
                          usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD']]) {
          // Last part
        }
      }
    }
  }
}
```

My script works but I would like it to be more concise and use the pipeline syntax maximally.

Thank for any help,
Côme
Reply all
Reply to author
Forward
0 new messages