1. Introduction
In this article, we will explore how to use the JenkinsAPI library in Python to build a Jenkins job and pass parameters to it. JenkinsAPI is a powerful Python library that provides a high-level interface to interact with Jenkins.
2. Installation
Before we can start using JenkinsAPI, we need to install it. You can install it using pip:
pip install jenkinsapi
3. Connecting to Jenkins
The first step is to connect to the Jenkins server. We can do this by creating a Jenkins instance and passing the Jenkins server URL and credentials:
from jenkinsapi.jenkins import Jenkins
jenkins_url = 'http://localhost:8080'
username = 'admin'
password = 'password'
jenkins = Jenkins(jenkins_url, username=username, password=password)
4. Building a Jenkins Job
Once we are connected to the Jenkins server, we can build a specific Jenkins job using its name. We can access a job by using the get_job()
method of the Jenkins instance, which returns a Job object. We can then call the invoke()
method of the Job object to trigger a build:
job_name = 'my-job'
job = jenkins.get_job(job_name)
job.invoke()
This will trigger a build for the job named 'my-job' in Jenkins.
4.1. Passing Parameters to the Jenkins Job
In order to pass parameters to the Jenkins job, we can use the invoke()
method's 'parameters' parameter. This parameter should be a dictionary where the keys are the parameter names and the values are their corresponding values.
parameters = {'temperature': '0.6'}
job.invoke(parameters=parameters)
In the above example, we are passing a parameter named 'temperature' with a value of '0.6' to the Jenkins job.
4.2. Setting Up Jenkins Job Parameters
In order for the Jenkins job to accept parameters, we need to configure the job in Jenkins. On the job's configuration page, click on 'This project is parameterized' and add the desired parameters. In our case, we would add a parameter named 'temperature' of type 'String'.
5. Conclusion
In this article, we explored how to use the JenkinsAPI library in Python to build a Jenkins job and pass parameters to it. We learned how to connect to a Jenkins server, trigger a build for a specific job, and pass parameters to the job. JenkinsAPI provides an easy-to-use interface for automating Jenkins job builds and integrations with other Python applications.
With the code examples provided, you should now be able to integrate Jenkins into your Python projects and automate the build process.