0

I currently have a git repo which has a text file. I want to load its contents as a build parameter for a jenkins job. One way would be to manually copy the contents of this file in Jenkins multi-line string parameter. But, since the content is in git already I want to keep it coupled.

Not sure, if this is even possible using Jenkins? I am using Jenkins Job DSL to generate the job.

iDev
  • 2,163
  • 10
  • 39
  • 64

2 Answers2

1

EDIT : You can find several different ways of achieving this in the following answer Jenkins dynamic declarative pipeline parameters

I think you can achieve it the following way (scripted pipeline).

node {
    stage("read file") {
        sh('echo -n "some text" > afile.txt')
        def fileContent = readFile('afile.txt')
        properties([
            parameters([
                string(name: 'FILE_CONTENT', defaultValue: fileContent)
            ])
        ])
    }
    stage("Display properties") {
        echo("${params.FILE_CONTENT}")
    }
}

The first time you execute it there will be no parameter choice. The second time, you'll have the option to build with parameter and the content will be the content of your file.

The bad thing with this approach is that it's always in sync with the previous execution, i.e. when you start the build on a commit where you changed the content of your file, it will prefill the parameter with the content of the file as per the last execution of the build.

The only way I know around this, is to split your pipeline into two pipelines. The first one reads the content of the file and then triggers the second one with the file content as build parameter with the build step.

If you find a better way let us know.

IppX
  • 305
  • 1
  • 13
  • The workaround you mentioned can be done with .jenkinsfile instead of .txt with this first Jenkinsfile can read the parameters with correct syntax, benefit is user can defined fault values using groovy. – np2807 May 12 '21 at 13:06
  • Wait, `readFile` AFAIK only reads the file content. Do you mean by using [load](https://www.jenkins.io/doc/pipeline/steps/workflow-cps/#load-evaluate-a-groovy-source-file-into-the-pipeline-script) ? – IppX May 26 '21 at 13:41
0

Why don't you have jenkins pull the repo as part of the Job, and then parse the contents of the parameters (in say, json, for example from a file within the repo) and then continue executing with those parameters?

Vizzyy
  • 522
  • 3
  • 11
  • yes, I could do that but the text in the file needs to be shown as default value of multi-line string parameter. So was wondering if this is even possible? – iDev May 07 '21 at 21:04
  • You can define your job via declarative jenkins syntax in a Jenkinsfile. You could programatically set the value of the Job parameter to read from a file. – Vizzyy May 07 '21 at 21:50
  • this says you can do exactly what you're trying: https://dumbitdude.com/how-to-upload-a-file-in-jenkins-using-file-parameter/ – Vizzyy May 07 '21 at 21:50