Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins Declarative Pipeline: How to inject properties

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?

like image 413
P. Beatty Avatar asked Feb 15 '17 14:02

P. Beatty


People also ask

How do you inject environment variables to the build process?

We can install and use the EnvInject plugin to inject environment variables during the build startup. In the build configuration window, we select the “Inject environment variables” option in the “Add build step” combo box. We can then add the required environment variables in the properties content text box.


2 Answers

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.

like image 152
Jon S Avatar answered Nov 15 '22 10:11

Jon S


The Jon S answer 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']"
      }
    }
  }
}
like image 44
Dennis Hoer Avatar answered Nov 15 '22 10:11

Dennis Hoer