Jenkins Declarative Pipeline: How to inject properties

不羁的心 提交于 2019-12-01 06:12:15

You can use the script step inside the steps tag to run arbitrary pipeline code.

So something in the lines of:

pipeline {
    agent any
    stages {
        stage('A') {
            steps {
                writeFile file: 'props.txt', text: 'foo=bar'
                script {
                    def props = readProperties file:'props.txt';
                    env['foo'] = props['foo'];
                }
            }
        }
        stage('B') {
            steps {
                echo env.foo
            }
        }
    }
}

Here I'm using env to propagate the values between stages, but it might be possible to do other solutions.

To define general vars available to all stages, define values for example in 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}
      }
   }
}

The @jon-s solution requires granting script approval because it is setting environment variables. This is not needed when running in same stage.

pipeline {
  agent any
  stages {
    stage('A') {
      steps {
        writeFile file: 'props.txt', text: 'foo=bar'
        script {
           def props = readProperties file:'props.txt';
        }
        sh "echo $props['foo']"
      }
    }
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!