0

I started to use Jenkins recently. I provides two parameters to collect the dynamic settings and would use them in later stage/steps part (in a bash script). I refer some examples such as

https://github.com/jenkinsci/pipeline-examples/blob/master/declarative-examples/jenkinsfile-examples/mavenDocker.groovy

I tried to use parmeter directly or by though environment, multiple combinations, single quote, double quote, etc. But the value gathered from parameters still could NOT been successfully passed to bash command. I believed that this is a very basic requirement but I can not find the proper working example.

Here is my sample code.

pipeline {

  agent {
    docker {
      image ...
      args ...
    }
  }

  environment {
    USERNAME = ${params.E_USERNANE}
    BRANCH = ${params.E_BRANCH}
  }

  parameters {
    string(name: 'E_USERNANE', defaultValue: 'githubuser', description: 'Please input the username')
    string(name: 'E_BRANCH', defaultValue: 'dev', description: 'Please input the git branch you want to test')
  }

  stages {
    stage('build') {
      steps {
        echo "username: ${params.E_USERNANE}"
        echo "branch: ${params.E_BRANCH}"
        echo E_USERNANE
        echo E_BRANCH
        sh """
          echo ${USERNAME} > /mydata/1.tmp
          echo ${BRANCH} >> /mydata/1.tmp
        """
      }
    }
  }
}      
Yongzhi.C
  • 141
  • 1
  • 2
  • 9

1 Answers1

0

My awesome colleague just helped me figure this out. We should change environment part as follow:

  environment {
    USERNAME = "${params.E_USERNANE}"
    BRANCH = "${params.E_BRANCH}"
  }

The parameters are gathered and passed to environment, then defining environment variables would be used in instructing scripts. See more at jenkins.io/doc/pipeline/tour/environment.

I would like to include lvthillo's solution here as well. We could remove environment{} part and use the following bash scripts within stage/steps instead to achieve the same goal.

sh """
echo "${params.E_USERNANE}" > /mydata/1.tmp
echo "${params.E_BRANCH}" >> /mydata/1.tmp
"""
Yongzhi.C
  • 141
  • 1
  • 2
  • 9
  • 1
    you can just use "${params.E_USERNANE}" or params.E_USERNAME (outside bash) without declaring environment variables for your parameters – lvthillo Aug 25 '18 at 21:12
  • Yes, you are right. The tricky syntax of single quote Vs. double quote and in Vs. out bash ever confused me. I tried a few combinations but got empty string, 'null', or Jenkins syntax error... Thanks lvthillo for your simple solution. – Yongzhi.C Aug 27 '18 at 19:05