Jenkinsfile Declarative Pipeline defining dynamic env vars

回眸只為那壹抹淺笑 提交于 2019-11-27 06:44:19

You can create variables before the pipeline block starts. You can have sh return stdout to assign to these variables. You don't have the same flexibility to assign to environment variables in the environment stanza. So substitute in python3.5 get_version.py where I have echo 0.0.1 in the script here (and make sure your python script just returns the version to stdout):

def awesomeVersion = 'UNKNOWN'

pipeline {
  agent { label 'docker' }
  stages {
    stage('build') {
      steps {
        script {
          awesomeVersion = sh(returnStdout: true, script: 'echo 0.0.1')
        }
      }
    }
    stage('output_version') {
      steps {
        echo "awesomeVersion: ${awesomeVersion}"
      }
    }
  }
}

The output of the above pipeline is:

awesomeVersion: 0.0.1

In Jenkins 2.76 I was able to simplify the solution from @burnettk to:

pipeline {
  agent { label 'docker' }
  environment {
    awesomeVersion = sh(returnStdout: true, script: 'echo 0.0.1')
  }
  stages {
    stage('output_version') {
      steps {
        echo "awesomeVersion: ${awesomeVersion}"
      }
    }
  }
}

Using the "pipeline utility steps" plugin, you can define general vars available to all stages from a properties file. For example, let props.txt as:

version=1.0
fix=alfa

and mix script and declarative Jenkins pipeline as:

def props
def VERSION
def FIX
def RELEASE

node {
   props = readProperties file:'props.txt'
   VERSION = props['version']
   FIX = props['fix']
   RELEASE = VERSION + "_" + FIX
}

pipeline {
   stages {
      stage('Build') {
         echo ${RELEASE}
      }
   }
}

You can also dump all your vars into a file, and then use the '-e @file' syntax. This is very useful if you have many vars to populate.

steps {
  echo "hello World!!"
  sh """
  var1: ${params.var1}
  var2: ${params.var2}
  " > vars
  """
  ansiblePlaybook inventory: _inventory, playbook: 'test-playbook.yml', sudoUser: null, extras: '-e @vars'
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!