JJB (Jenkins Job Builder) How to propagate variable into pipeline script?

126 views Asked by At

I want to reuse one groovy script creating multiple jobs based on it.
It looks good when you have similar jobs.
I have something like this:

my_definition.yml

- project:
    name: my-project
    jobs:
        - my-jobs

- job-group:
    name: my-jobs
    jobs:
        - "{job-name}_job":
            job-name: '1'
            file-path: "./path/to/my_job.groovy"
            var1: "smth" <-- here
- job-template:
    name: "{job-name}_job"
    project-type: pipeline
    concurrent: true
    dsl: !include-raw: "{file-path}"

my_job.groovy

pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                echo '{var1}' <-- here
            }
        }
    }
}

The output:

...
    <script>pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                echo '{var1}'
            }
        }
    }
}
</script>
...

Expected:

...
    <script>pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                echo 'smth'
            }
        }
    }
}
</script>
...

Is there any way in JJB to do like this?

JJB version: jjb --version
Jenkins Job Builder version: 3.11.0

1

There are 1 answers

0
hshib On

It works with version 5.1.0, but not with 4.3.0.

But also, you have to escape the "{}" characters since they are processed for string formatting. So your script needs to be like:

pipeline {{
    agent any
    stages {{
        stage('Example') {{
            steps {{
                echo '{var1}'
            }}
        }}
    }}
}}

With 5.1.0 and this change, output will come out as:

<flow-definition plugin="workflow-job">
  <definition class="org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition" plugin="workflow-cps">
    <script>pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                echo 'smth'
            }
        }
    }
}
</script>