Jenkins Declarative Pipeline: How to inject properties

回眸只為那壹抹淺笑 提交于 2019-12-01 04:31:03

问题


I have Jenkins 2.19.4 with Pipeline: Declarative Agent API 1.0.1. How does one use readProperties if you cannot define a variable to assign properties read to?

For example, to capture SVN revision number, I currently capture it with following in Script style:

```

echo "SVN_REVISION=\$(svn info ${svnUrl}/projects | \
grep Revision | \
sed 's/Revision: //g')" > svnrev.txt

```

def svnProp = readProperties file: 'svnrev.txt'

Then I can access using:

${svnProp['SVN_REVISION']}

Since it is not legal to def svnProp in Declarative style, how is readProperties used?


回答1:


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.




回答2:


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']"
      }
    }
  }
}



回答3:


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}
      }
   }
}


来源:https://stackoverflow.com/questions/42252552/jenkins-declarative-pipeline-how-to-inject-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!