"Running Jenkins Job with File Inputs using JenkinsAPI"
The main objective of the tutorial is to run a Jenkins job with file inputs using the JenkinsAPI.
Level: Intermediate
JenkinsApi library provides an interface to access resources on the Jenkins server in conventional Python objects to make most Jenkins-oriented tasks simpler. To install and explore JenkinsApi access links in the reference section.
Following is a Jenkins job sample_job
that takes a single argument of type Stashed File Parameter
.
Below Python code below initializes a Jenkins server and triggers the sample_job
followed by the explanation of various functions used.
from jenkinsapi.jenkins import Jenkins
from os import getenv
jenkins_url: str = getenv("JENKINS_URL")
jenkins_username: str = getenv("JENKINS_USERNAME")
jenkins_password: str = getenv("JENKINS_PASSWORD")
def init_jenkins() -> Jenkins:
print("initializing jenkins server.")
server = Jenkins(baseurl=jenkins_url, username=jenkins_username, password=jenkins_password)
print("jenkins initialized.")
return server
def run_job(server: Jenkins, job_name, *, build_params={}, files={}):
job = server.get_job(job_name)
job.invoke(build_params=build_params, files=files)
print("Your job is triggered, view job console for execution logs.")
# Driver Code
server = init_jenkins()
job_files_input = {}
config_json_file_path = <YOUR FILE PATH HERE> / "duoknowledge.json"
with open(config_json_file_path, "r") as config_file:
job_files_input["duoknowledge_json"] = config_file.read()
run_job(
server,
"sample_job",
files=job_files_input,
)
Jenkins
injenkinsapi.jenkins
Represents a Jenkins environment.
- param baseurl: baseurl for jenkins instance including port, str
- param username: username for jenkins auth, str
- param password: password for jenkins auth, str
- return: a Jenkins objget_job()
is used to get a job by name
- param jobname: name of the job, str
- return: Job objinvoke()
is used to trigger the job.
- param build_params: job input parameter for input type other than file.
- param files: job input parameter forStashed File Parameter
.
- param block: bool to block python execution until job execution is complete.
- return: QueueItem
References:
- https://pypi.org/project/jenkinsapi/
- https://jenkinsapi.readthedocs.io/en/latest/