如何在Jenkins Job Builder中通过变量列表实现Multijob项目的动态配置
Hey Archna, welcome to the Jenkins and YAML world! Let's walk through exactly how to set up that dynamic job list using Jenkins Job Builder (JJB) — it's all about leveraging JJB's built-in Jinja2 templating support. Here are two straightforward approaches to achieve what you need:
Approach 1: Direct Loop in the Multijob Projects Section
This is the simplest way — we'll define a list of your job names, then loop through it directly in the projects block to generate each entry:
# First, define your list of sub-job names as a variable job_names: ["JobA", "JobB"] job: name: test_job project-type: multijob builders: - multijob: name: PhaseOne condition: SUCCESSFUL projects: {% for job in job_names %} - name: {{ job }} current-parameters: true {% endfor %}
How this works:
- We start by declaring
job_namesas a list containing your target sub-job names (JobA,JobB). - Using Jinja2's
{% for %}loop, we iterate over each name in the list. For every iteration, we generate a full job entry with thenameset to the current list item andcurrent-parameters: true. - When JJB processes this YAML, it will expand the loop into exactly the static project list you're aiming for.
Approach 2: Pre-define a Reusable JobsList Variable
If you want to explicitly create a JobsList variable first (like you mentioned in your question), you can do that too. This requires enabling Jinja2's do extension to modify lists:
Step 1: Update your JJB Configuration
First, add the jinja2.ext.do extension to your jenkins_jobs.ini file (usually located in /etc/jenkins_jobs/ or your user directory):
[job_builder] enable_jinja=True jinja_extensions=jinja2.ext.do # Keep your other existing config options here
Step 2: Write the Templated YAML
# Define your base list of job names job_suffixes: ["JobA", "JobB"] # Create and populate the JobsList variable {% set JobsList = [] %} {% for suffix in job_suffixes %} {% do JobsList.append({ 'name': suffix, 'current-parameters': true }) %} {% endfor %} job: name: test_job project-type: multijob builders: - multijob: name: PhaseOne condition: SUCCESSFUL projects: {{ JobsList }}
How this works:
- We initialize an empty
JobsListwith{% set %}. - Using the
{% do %}directive (from the enabled extension), we append a dictionary for each job name injob_suffixes— each dictionary has the requirednameandcurrent-parameterskeys. - Finally, we just reference
{{ JobsList }}in theprojectssection, and JJB will expand it into the full list of job entries.
Quick Notes:
- Make sure your JJB version supports Jinja2 templating (most recent versions do, but double-check if you're on an older install).
- If you need to add other parameters (like
git-revisionorproperty-file) for specific jobs, you can adjust the loop logic to handle conditional values too.
内容的提问来源于stack exchange,提问作者Archna Mittal

