### Start Parameterized Jenkins Builds using JenkinsAPI Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/examples.md This example demonstrates how to start a parameterized Jenkins build. It shows both non-blocking and blocking methods for triggering builds and retrieving build results. Requires the `jenkinsapi` library. ```python from jenkinsapi.jenkins import Jenkins jenkins = Jenkins("http://localhost:8080") params = {"VERSION": "1.2.3", "PYTHON_VER": "2.7"} # This will start the job in non-blocking manner jenkins.build_job("foo", params) # This will start the job and will return a QueueItem object which # can be used to get build results job = jenkins["foo"] qi = job.invoke(build_params=params) # Block this script until build is finished if qi.is_queued() or qi.is_running(): qi.block_until_complete() build = qi.get_build() print(build) ``` -------------------------------- ### Retrieve Jenkins Plugin Information Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/examples.md Demonstrates how to connect to a Jenkins instance and retrieve details about an installed plugin by name. It uses the Jenkins class to access the plugin registry. ```python from jenkinsapi.jenkins import Jenkins plugin_name = "subversion" jenkins = Jenkins("http://localhost:8080") plugin = jenkins.get_plugins()[plugin_name] print(repr(plugin)) ``` -------------------------------- ### Create and Manage Jenkins Views Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/examples.md Illustrates how to create, manage, and delete different types of views in Jenkins, including ListView and CategorizedJobsView. It also shows how to add jobs to a view. This example requires the 'jenkinsapi' library and assumes a running Jenkins instance. ```python import logging from pkg_resources import resource_string from jenkinsapi.jenkins import Jenkins logging.basicConfig(level=logging.INFO) logger = logging.getLogger() jenkins_url = "http://localhost:8080/" jenkins = Jenkins(jenkins_url, lazy=True) # Create ListView in main view logger.info("Attempting to create new view") test_view_name = "SimpleListView" # Views object appears as a dictionary of views if test_view_name not in jenkins.views: new_view = jenkins.views.create(test_view_name) if new_view is None: logger.error("View %s was not created", test_view_name) else: logger.info( "View %s has been created: %s", new_view.name, new_view.baseurl ) else: logger.info("View %s already exists", test_view_name) # No error is raised if view already exists logger.info("Attempting to create view that already exists") my_view = jenkins.views.create(test_view_name) logger.info("Create job and assign it to a view") job_name = "foo_job2" xml = resource_string("examples", "addjob.xml") my_job = jenkins.create_job(jobname=job_name, xml=xml) # add_job supports two parameters: job_name and job object # passing job object will remove verification calls to Jenkins my_view.add_job(job_name, my_job) assert len(my_view) == 1 logger.info("Attempting to delete view that already exists") del jenkins.views[test_view_name] if test_view_name in jenkins.views: logger.error("View was not deleted") else: logger.info("View has been deleted") # No error will be raised when attempting to remove non-existing view logger.info("Attempting to delete view that does not exist") del jenkins.views[test_view_name] # Create CategorizedJobsView config = """ .dev. Development .hml. Homologation """ view = jenkins.views.create( "My categorized jobs view", jenkins.views.CATEGORIZED_VIEW, config=config ) ``` -------------------------------- ### Create and Delete Jenkins Jobs from XML using JenkinsAPI Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/examples.md This example demonstrates how to create a Jenkins job from an XML configuration file and subsequently delete it. It utilizes `pkg_resources` to load the XML content and the `jenkinsapi` library for job management. Requires `jenkinsapi` and `pkg_resources`. ```python from pkg_resources import resource_string from jenkinsapi.jenkins import Jenkins jenkins = Jenkins("http://localhost:8080") job_name = "foo_job2" xml = resource_string("examples", "addjob.xml") print(xml) job = jenkins.create_job(jobname=job_name, xml=xml) # Get job from Jenkins by job name my_job = jenkins[job_name] print(my_job) # also can use # del jenkins[job_name] jenkins.delete_job(job_name) ``` -------------------------------- ### Install Jenkinsapi package Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/readme_link.md Command to install the Jenkinsapi library using pip. ```bash pip install jenkinsapi ``` -------------------------------- ### Configure Jenkins Slaves/Nodes using JenkinsAPI Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/examples.md This example demonstrates how to configure Jenkins slaves or nodes, including setting up authentication. It uses the `jenkinsapi` library and `requests` for handling potential SSL warnings. Requires `jenkinsapi`, `requests`, and `logging`. ```python import logging import requests from jenkinsapi.jenkins import Jenkins from jenkinsapi.utils.requester import Requester requests.packages.urllib3.disable_warnings() log_level = getattr(logging, "DEBUG") logging.basicConfig(level=log_level) logger = logging.getLogger() jenkins_url = "http://localhost:8080/" username = "default_user" # In case Jenkins requires authentication password = "default_password" jenkins = Jenkins( jenkins_url, requester=Requester( username, password, baseurl=jenkins_url, ssl_verify=False ), ) ``` -------------------------------- ### Manage Nested Views in Jenkins Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/examples.md Demonstrates the creation, manipulation, and deletion of NestedViews in Jenkins. This requires the NestedViews plugin to be installed on the target Jenkins server. ```python import logging from pkg_resources import resource_string from jenkinsapi.views import Views from jenkinsapi.jenkins import Jenkins jenkins = Jenkins("http://127.0.0.1:8080/") job_name = "foo_job2" xml = resource_string("examples", "addjob.xml") j = jenkins.create_job(jobname=job_name, xml=xml) top_view = jenkins.views.create("TopView", Views.NESTED_VIEW) sub_view = top_view.views.create("SubView") del top_view.views["SubView"] top_view.views["SubView"] = job_name del jenkins.views["TopView"] jenkins.delete_job(job_name) ``` -------------------------------- ### Create Credentials in Jenkins using JenkinsAPI Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/examples.md This example illustrates how to create different types of credentials (username/password, SSH keys) in Jenkins using the JenkinsAPI. It covers retrieving existing credentials, adding new ones, and removing them. Requires `jenkinsapi` and the `logging` module. ```python import logging from jenkinsapi.jenkins import Jenkins from jenkinsapi.credential import UsernamePasswordCredential, SSHKeyCredential log_level = getattr(logging, "DEBUG") logging.basicConfig(level=log_level) logger = logging.getLogger() jenkins_url = "http://localhost:8080/" jenkins = Jenkins(jenkins_url) # Get a list of all global credentials creds = jenkins.credentials logging.info(jenkins.credentials.keys()) # Create username and password credential creds_description1 = "My_username_credential" cred_dict = { "description": creds_description1, "userName": "userName", "password": "password", } creds[creds_description1] = UsernamePasswordCredential(cred_dict) # Create ssh key credential that uses private key as a value # In jenkins credential dialog you need to paste credential # In your code it is advised to read it from file # For simplicity of this example reading key from file is not shown here def get_private_key_from_file(): return "-----BEGIN RSA PRIVATE KEY-----" my_private_key = get_private_key_from_file() creds_description2 = "My_ssh_cred1" cred_dict = { "description": creds_description2, "userName": "userName", "passphrase": "", "private_key": my_private_key, } creds[creds_description2] = SSHKeyCredential(cred_dict) # Create ssh key credential that uses private key from path on Jenkins server my_private_key = "/home/jenkins/.ssh/special_key" creds_description3 = "My_ssh_cred2" cred_dict = { "description": creds_description3, "userName": "userName", "passphrase": "", "private_key": my_private_key, } creds[creds_description3] = SSHKeyCredential(cred_dict) # Remove credentials # We use credential description to find specific credential. This is the only # way to get specific credential from Jenkins via REST API del creds[creds_description1] del creds[creds_description2] del creds[creds_description3] # Remove all credentials for cred_descr in creds.keys(): del creds[cred_descr] ``` -------------------------------- ### Create a Jenkins view using jenkins.views.create() Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/low_level_examples.md This example shows how to create a new Jenkins view using the `jenkins.views.create()` method. It utilizes the `json` and `requests` libraries. The input includes the view name and type, and the output is the text response from the Jenkins API. ```python import json import requests url = "http://localhost:8080/createView" str_view_name = "blahblah123" params = {} # {'name': str_view_name} headers = {"Content-Type": "application/x-www-form-urlencoded"} data = { "name": str_view_name, "mode": "hudson.model.ListView", "Submit": "OK", "json": json.dumps( {"name": str_view_name, "mode": "hudson.model.ListView"} ), } # Try 1 result = requests.post(url, params=params, data=data, headers=headers) print(result.text.encode("UTF-8")) ``` -------------------------------- ### Clone JenkinsAPI Project and Install Dependencies (Bash) Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/index.md Clones the JenkinsAPI project from GitHub into a 'src' directory and installs Python dependencies using 'uv'. It also sets up and runs tests using pytest. ```bash cd jenkinsapi git clone https://github.com/pycontribs/jenkinsapi.git src uv venv uv python install uv run pytest -sv --cov=jenkinsapi --cov-report=term-missing --cov-report=xml jenkinsapi_tests ``` -------------------------------- ### Install Jenkinsapi in development mode Source: https://github.com/pycontribs/jenkinsapi/blob/master/README.rst This command installs the Jenkinsapi package in development mode using `uv`. This typically involves installing the package and its development dependencies. ```bash uv sync ``` -------------------------------- ### JenkinsAPI login with authentication Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/low_level_examples.md This example shows how to authenticate with Jenkins using `jenkinsapi` by providing a username and password. It imports the `jenkins` module and initializes a `Jenkins` object with connection details. The `poll()` method is called to check connectivity, and `items()` retrieves job information. ```python from jenkinsapi import jenkins J = jenkins.Jenkins("http://localhost:8080", username="sal", password="foobar") J.poll() print(J.items()) ``` -------------------------------- ### Basic Jenkins Interaction Example Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/getting_started.md Demonstrates basic interaction with a Jenkins server using JenkinsAPI. It shows how to connect to a server, retrieve its version, list jobs, and access a specific job. ```python from jenkinsapi.jenkins import Jenkins J = Jenkins('http://localhost:8080') print(J.version) # 1.542 print(J.keys()) # foo, test_jenkinsapi print(J.get('test_jenkinsapi')) # print(J.get('test_jenkinsapi').get_last_good_build()) # ``` -------------------------------- ### Get Jenkins Plugin Details Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/getting_started.md Retrieves and prints details of all installed plugins on a Jenkins instance. It iterates through the plugins and displays their short name, long name, version, URL, and active/enabled status. ```python def get_plugin_details(): # Refer Example #1 for definition of function 'get_server_instance' server = get_server_instance() for plugin in server.get_plugins().values(): print "Short Name:%s" % (plugin.shortName) print "Long Name:%s" % (plugin.longName) print "Version:%s" % (plugin.version) print "URL:%s" % (plugin.url) print "Active:%s" % (plugin.active) print "Enabled:%s" % (plugin.enabled) ``` -------------------------------- ### Manage Jenkins Plugins Source: https://context7.com/pycontribs/jenkinsapi/llms.txt Provides methods to list installed plugins, verify installation status, install new plugins, and remove existing ones. Includes logic for handling restarts when required by plugin changes. ```python from jenkinsapi.jenkins import Jenkins jenkins = Jenkins("http://localhost:8080") # List installed plugins plugins = jenkins.plugins for plugin_name in plugins.keys(): plugin = plugins[plugin_name] print(f"{plugin_name}: {plugin.version}") # Check if plugin is installed if jenkins.has_plugin("git"): print("Git plugin is installed") # Install a plugin (with optional restart) jenkins.install_plugin("kubernetes", restart=True, wait_for_reboot=True) # Install multiple plugins plugin_list = ["docker-workflow", "pipeline-stage-view", "blueocean"] jenkins.install_plugins(plugin_list, restart=True, wait_for_reboot=True) # Delete a plugin jenkins.delete_plugin("deprecated-plugin", restart=True) # Check if restart is required if plugins.restart_required: jenkins.safe_restart(wait_for_reboot=True) ``` -------------------------------- ### Fetch Jenkins Job Configuration XML Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/examples.md Demonstrates how to retrieve the configuration XML for a specific job in Jenkins using the Jenkins API. It fetches the first job from the Jenkins instance and prints its configuration. This is useful for inspecting or backing up job configurations. Requires the 'jenkinsapi' library. ```python from jenkinsapi.jenkins import Jenkins jenkins = Jenkins("http://localhost:8080") jobName = jenkins.keys()[0] # get the first job config = jenkins[jobName].get_config() print(config) ``` -------------------------------- ### Get JenkinsAPI Version (Bash) Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/index.md A command-line utility to retrieve the installed version of JenkinsAPI. This is a simpler alternative to the Python script for quick checks. ```bash jenkinsapi_version ``` -------------------------------- ### Copy an existing Jenkins job using jenkins.copy_job() Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/low_level_examples.md This example demonstrates how to copy an existing Jenkins job using the `jenkins.copy_job()` method. It requires the `requests`, `pkg_resources`, and `jenkinsapi` libraries. The input is the name of the existing job and the desired name for the new job. The output is the response text from the Jenkins API. ```python import requests from pkg_resources import resource_string from jenkinsapi.jenkins import Jenkins from jenkinsapi_tests.test_utils.random_strings import random_string J = Jenkins("http://localhost:8080") jobName = random_string() jobName2 = "%s_2" % jobName url = "http://localhost:8080/createItem?from=%s&name=%s&mode=copy" % ( jobName, jobName2, ) xml = resource_string("examples", "addjob.xml") j = J.create_job(jobname=jobName, xml=xml) h = {"Content-Type": "application/x-www-form-urlencoded"} response = requests.post(url, data="dysjsjsjs", headers=h) print(response.text.encode("UTF-8")) ``` -------------------------------- ### Run a parameterized Jenkins build using jenkins.build_job() Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/low_level_examples.md This Python example demonstrates how to trigger a parameterized build for a Jenkins job using `jenkins.build_job()`. It requires the `json` and `requests` libraries. The input is a JSON object containing build parameters, and the output is the response from the Jenkins API. ```python import json import requests tooJson = {"parameter": [{"name": "B", "value": "xyz"}]} url = "http://localhost:8080/job/ddd/build" # url = 'http://localhost:8000' headers = {"Content-Type": "application/x-www-form-urlencoded"} form = {"json": json.dumps(toJson)} response = requests.post(url, data=form, headers=headers) print(response.text.encode("UTF-8")) ``` -------------------------------- ### Install Artifacts (Python) Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/submodules/api.md Installs a collection of artifacts into a specified directory structure. This function is useful for deploying build outputs. It requires a list of artifacts, a directory structure mapping, the installation directory, and a base URL for artifact retrieval. ```python from jenkinsapi.api import install_artifacts artifacts_to_install = ["artifact1.zip", "config.xml"] directory_structure = {"artifact1.zip": "libs/", "config.xml": "conf/"} install_location = "/opt/app/" base_url = "http://your-jenkins-server.com/job/deploy_job/lastSuccessfulBuild/artifact/" install_artifacts(artifacts_to_install, directory_structure, install_location, base_url) ``` -------------------------------- ### Add Command to Shell Build Step using JenkinsAPI Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/examples.md This example shows how to add a new command to the 'Shell' build step of a Jenkins job. It involves parsing the job's XML configuration, modifying the builders section, and updating the job configuration. Requires the `jenkinsapi` library. ```python import xml.etree.ElementTree as et from jenkinsapi.jenkins import Jenkins J = Jenkins("http://localhost:8080") EMPTY_JOB_CONFIG = """ jkkjjk false true false false false false """ jobname = "foo_job" new_job = J.create_job(jobname, EMPTY_JOB_CONFIG) new_conf = new_job.get_config() # Create in a folder (Folders plugin) folder_job = J.create_job("folder1/folder2/job-name", EMPTY_JOB_CONFIG) root = et.fromstring(new_conf.strip()) builders = root.find("builders") shell = et.SubElement(builders, "hudson.tasks.Shell") command = et.SubElement(shell, "command") command.text = "ls" print(et.tostring(root)) J[jobname].update_config(et.tostring(root)) ``` -------------------------------- ### Create JNLP and SSH Nodes in Jenkins Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/examples.md Demonstrates the creation of both JNLP (Java Webstart) and SSH nodes in Jenkins using the Jenkins API. It includes defining node properties, creating the nodes, and basic node management operations like taking nodes offline/online and deleting them. Requires the 'jenkinsapi' library. ```python node_dict = { "num_executors": 1, # Number of executors "node_description": "Test JNLP Node", # Just a user friendly text "remote_fs": "/tmp", # Remote workspace location "labels": "my_new_node", # Space separated labels string "exclusive": True, # Only run jobs assigned to it } new_jnlp_node = jenkins.nodes.create_node("My new webstart node", node_dict) node_dict = { "num_executors": 1, "node_description": "Test SSH Node", "remote_fs": "/tmp", "labels": "new_node", "exclusive": True, "host": "localhost", # Remote hostname "port": 22, # Remote post, usually 22 "credential_description": "localhost cred", # Credential to use # [Mandatory for SSH node!] # (see Credentials example) "jvm_options": "-Xmx2000M", # JVM parameters "java_path": "/bin/java", # Path to java "prefix_start_slave_cmd": "", "suffix_start_slave_cmd": "", "max_num_retries": 0, "retry_wait_time": 0, "retention": "OnDemand", # Change to 'Always' for # immediate slave launch "ondemand_delay": 1, "ondemand_idle_delay": 5, "env": [ # Environment variables {"key": "TEST", "value": "VALUE"}, {"key": "TEST2", "value": "value2"}, ], } new_ssh_node = jenkins.nodes.create_node("My new SSH node", node_dict) # Take this slave offline if new_ssh_node.is_online(): new_ssh_node.toggle_temporarily_offline() # Take this slave back online new_ssh_node.toggle_temporarily_offline() # Get a list of all slave names slave_names = jenkins.nodes.keys() # Get Node object my_node = jenkins.nodes["My new SSH node"] # Take this slave offline my_node.set_offline() # Delete slaves del jenkins.nodes["My new webstart node"] del jenkins.nodes["My new SSH node"] ``` -------------------------------- ### Authenticate with Jenkins Crumbs Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/examples.md Shows how to initialize a Jenkins connection with username/password authentication and CSRF crumb support. This is necessary for performing write operations on secured Jenkins instances. ```python from jenkinsapi.jenkins import Jenkins jenkins = Jenkins( "http://localhost:8080", username="admin", password="password", use_crumb=True, ) for job_name in jenkins.jobs: print(job_name) ``` -------------------------------- ### Search Jenkins Artifacts Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/examples.md Provides methods to search for build artifacts by exact name or by using regular expressions. These functions help locate specific files within a job's build history. ```python from jenkinsapi.api import search_artifacts jenkinsurl = "http://localhost:8080" jobid = "foo" artifact_ids = ["test1.txt", "test2.txt"] result = search_artifacts(jenkinsurl, jobid, artifact_ids) print((repr(result))) ``` ```python import re from jenkinsapi.api import search_artifact_by_regexp jenkinsurl = "http://localhost:8080" jobid = "foo" artifact_regexp = re.compile(r"test1\.txt") result = search_artifact_by_regexp(jenkinsurl, jobid, artifact_regexp) print((repr(result))) ``` -------------------------------- ### Configure JenkinsAPI Logging Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/examples.md This snippet shows how to configure the logging level for the JenkinsAPI library. It allows you to control the verbosity of logs, which can be helpful for debugging. Requires the `jenkinsapi` library. ```python from jenkinsapi.utils.logging import configure_logging configure_logging("DEBUG") ``` -------------------------------- ### Manage Jenkins Build Artifacts Source: https://context7.com/pycontribs/jenkinsapi/llms.txt Provides examples for downloading and managing build artifacts. It covers retrieving all artifacts from a build, saving artifacts to local paths or directories, accessing artifact content, and searching for artifacts across builds using specific IDs or regular expressions. ```python from jenkinsapi.jenkins import Jenkins from jenkinsapi.api import search_artifacts, search_artifact_by_regexp import re jenkins = Jenkins("http://localhost:8080") job = jenkins["my-job"] build = job.get_last_good_build() # Get all artifacts from a build for artifact in build.get_artifacts(): print(f"Artifact: {artifact.filename}") print(f"URL: {artifact.url}") # Save artifact to a specific path artifact.save("/tmp/downloads/myfile.zip") # Save artifact to a directory (uses original filename) artifact.save_to_dir("/tmp/downloads/") # Get artifact content as bytes data = artifact.get_data() # Get artifacts as dictionary (keyed by relative path) artifacts = build.get_artifact_dict() print(artifacts.keys()) # ['target/app.jar', 'reports/test.xml'] # Access specific artifact jar_artifact = artifacts["target/app.jar"] jar_artifact.save("/tmp/app.jar", strict_validation=True) # Search for artifacts across all builds artifacts = search_artifacts( jenkinsurl="http://localhost:8080", jobname="my-job", artifact_ids=["app.jar", "config.xml"] ) # Search artifacts by regex pattern import re artifact = search_artifact_by_regexp( jenkinsurl="http://localhost:8080", jobname="my-job", artifactRegExp=re.compile(r"app-\d+\.\d+\.jar") ) print(artifact.filename) # "app-1.2.jar" ``` -------------------------------- ### Get details of running Jenkins jobs Source: https://github.com/pycontribs/jenkinsapi/blob/master/README.rst This Python function retrieves and prints details for each job running on a Jenkins instance. It assumes a `get_server_instance` function is defined elsewhere to establish a connection to the Jenkins server. ```python """Get job details of each job that is running on the Jenkins instance""" def get_job_details(): # Refer Example #1 for definition of function 'get_server_instance' server = get_server_instance() for job_name, job_instance in server.get_jobs(): print 'Job Name:%s' % (job_instance.name) print 'Job Description:%s' % (job_instance.get_description()) print 'Is Job running:%s' % (job_instance.is_running()) print 'Is Job enabled:%s' % (job_instance.is_enabled()) ``` -------------------------------- ### Run pytest for Jenkinsapi development Source: https://github.com/pycontribs/jenkinsapi/blob/master/README.rst This command executes the pytest test suite for the Jenkinsapi project. It assumes pytest is installed and configured within a virtual environment managed by `uv`. ```bash uv run pytest -sv ``` -------------------------------- ### Watch POST requests with a Python HTTP server Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/low_level_examples.md This Python code sets up a simple HTTP server to watch and log incoming POST requests. It uses the `http.server`, `socketserver`, `logging`, and `cgi` modules. The server listens on a specified port and logs request headers and form data, providing insight into how JenkinsAPI might handle POST requests. ```python import http.server as SimpleHTTPServer import socketserver import logging import cgi PORT = 8081 # <-- change this to be the actual port you want to run on INTERFACE = "localhost" class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(self): logging.warning("======= GET STARTED ======='") logging.warning(self.headers) SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) def do_POST(self): logging.warning("======= POST STARTED ======='") logging.warning(self.headers) form = cgi.FieldStorage( fp=self.rfile, headers=self.headers, environ={ "REQUEST_METHOD": "POST", "CONTENT_TYPE": self.headers["Content-Type"], }, ) logging.warning("======= POST VALUES ======='") for item in form.list: logging.warning(item) logging.warning("\n") SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) Handler = ServerHandler httpd = socketserver.TCPServer(("", PORT), Handler) print( "Serving at: http://%(interface)s:%(port)s" % dict(interface=INTERFACE or "localhost", port=PORT) ) httpd.serve_forever() ``` -------------------------------- ### Get Jenkins Server Version Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/getting_started.md Retrieves the version of a Jenkins server. This function connects to a Jenkins instance using provided credentials and prints its version. ```python from jenkinsapi.jenkins import Jenkins def get_server_instance(): jenkins_url = 'http://jenkins_host:8080' server = Jenkins(jenkins_url, username='foouser', password='foopassword') return server if __name__ == '__main__': print get_server_instance().version ``` -------------------------------- ### Grab and Install Artifact (Python) Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/submodules/api.md Downloads a specific artifact from the latest successful build of a Jenkins job and saves it to a local directory. Creates the target directory if it doesn't exist. Requires Jenkins URL, job name, artifact identifier, target directory, and optional authentication. ```python from jenkinsapi.api import grab_artifact import os j নিরাপত্তা_url = "http://your-jenkins-server.com" job_name = "artifact_job" artifact_id = "my_app.jar" target_directory = "./downloaded_artifacts" grab_artifact(jenkins_url, job_name, artifact_id, target_directory) print(f"Artifact '{artifact_id}' downloaded to '{target_directory}'") ``` -------------------------------- ### Manage Jenkins Nodes (Slaves) with jenkinsapi Source: https://context7.com/pycontribs/jenkinsapi/llms.txt Provides examples for listing, accessing, monitoring, creating, modifying, and deleting Jenkins nodes (build agents). Supports JNLP and SSH node types. SSH node creation requires the SSH Credentials plugin. ```python from jenkinsapi.jenkins import Jenkins jenkins = Jenkins("http://localhost:8080") # List all nodes for node_name in jenkins.nodes.keys(): print(node_name) # Get node object node = jenkins.nodes["my-slave"] # or node = jenkins.get_node("my-slave") # Node status print(f"Is online: {node.is_online()}") print(f"Is idle: {node.is_idle()}") print(f"Is temporarily offline: {node.is_temporarily_offline()}") print(f"Offline reason: {node.offline_reason()}") # Node information print(f"Architecture: {node.get_architecture()}") print(f"Executors: {node.get_num_executors()}") print(f"Labels: {node.get_labels()}") # Take node offline/online node.set_offline("Maintenance in progress") node.set_online() # Create JNLP (Java Webstart) node node_config = { "num_executors": 2, "node_description": "Build agent for Java projects", "remote_fs": "/var/lib/jenkins", "labels": "linux java maven", "exclusive": False } new_node = jenkins.create_node("my-jnlp-agent", **node_config) # Create SSH node (requires SSH Credentials plugin) ssh_node_config = { "num_executors": 4, "node_description": "SSH Build Agent", "remote_fs": "/home/jenkins", "labels": "linux docker", "exclusive": True, "host": "agent.example.com", "port": 22, "credential_description": "jenkins-ssh-key", "jvm_options": "-Xmx2g", "java_path": "/usr/bin/java", "max_num_retries": 3, "retry_wait_time": 10 } ssh_node = jenkins.nodes.create_node("my-ssh-agent", ssh_node_config) # Modify node labels node.add_labels("new-label another-label") node.delete_labels("old-label") node.modify_labels(["label1", "label2"]) # Replace all labels # Set number of executors node.set_num_executors(4) # Delete node del jenkins.nodes["my-slave"] # or jenkins.delete_node("my-slave") # Block until node is idle node.block_until_idle(timeout=300, poll_time=10) ``` -------------------------------- ### Get JenkinsAPI Version (Python) Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/index.md Retrieves the installed version of the JenkinsAPI package using its __version__ attribute. This follows PEP-396 for versioning. ```python import jenkinsapi print(jenkinsapi.__version__) ``` -------------------------------- ### Initialize Jenkins Connection Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/submodules/jenkins.md Demonstrates how to instantiate the Jenkins client to connect to a server. It requires the base URL and supports optional authentication and configuration parameters. ```python from jenkinsapi.jenkins import Jenkins # Initialize the Jenkins object server = Jenkins( baseurl="http://localhost:8080", username="admin", password="password", timeout=10 ) ``` -------------------------------- ### Get Last Good Build Revision Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/examples.md Retrieves the revision number from the last successful build of a specific Jenkins job. It requires the job name and a connection to the Jenkins server. ```python from jenkinsapi.jenkins import Jenkins job_name = "foo" jenkins = Jenkins("http://localhost:8080") job = jenkins[job_name] lgb = job.get_last_good_build() print(lgb.get_revision()) ``` -------------------------------- ### Development environment commands Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/readme_link.md Commands for setting up the development environment and running tests using uv. ```bash uv sync uv run pytest -sv ``` -------------------------------- ### Connect to Jenkins and Retrieve Build Information Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/index.md Demonstrates how to initialize a Jenkins connection and access job objects to retrieve the last successful build. ```python import jenkinsapi from jenkinsapi.jenkins import Jenkins J = Jenkins('http://localhost:8080') J.keys() # Jenkins objects appear to be dict-like, mapping keys (job-names) to ['foo', 'test_jenkinsapi'] J['test_jenkinsapi'] # J['test_jenkinsapi'].get_last_good_build() # ``` -------------------------------- ### Initialize and Query Jenkins Label Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/submodules/label.md Demonstrates how to instantiate a Label object and retrieve associated job information. This class requires a base URL, label name, and a reference to the Jenkins object. ```python from jenkinsapi.label import Label # Initialize the label object label = Label(baseurl="http://jenkins:8080", labelname="my-label", jenkins_obj=jenkins_instance) # Check if the label is online is_online = label.is_online() # Get names of jobs tied to this label tied_jobs = label.get_tied_job_names() ``` -------------------------------- ### Create and Configure Jenkins Jobs via XML Source: https://context7.com/pycontribs/jenkinsapi/llms.txt Explains how to create new jobs using XML configuration strings, including support for folders and job manipulation. It also demonstrates updating existing configurations using the ElementTree library. ```python from jenkinsapi.jenkins import Jenkins import xml.etree.ElementTree as ET jenkins = Jenkins("http://localhost:8080") JOB_CONFIG_XML = """ My automated job echo "Hello World" """ # Create a new job new_job = jenkins.create_job("my-new-job", JOB_CONFIG_XML) # Create job inside folders folder_job = jenkins.create_job("folder1/folder2/job-name", JOB_CONFIG_XML) # Update job configuration job = jenkins["my-new-job"] config = job.get_config() root = ET.fromstring(config) # Modify configuration description = root.find("description") description.text = "Updated description" job.update_config(ET.tostring(root, encoding="unicode")) ``` -------------------------------- ### Node Configuration and Labels Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/submodules/nodes.md APIs for managing node labels, configuration, and specific configuration elements. ```APIDOC ## PUT /node/labels ### Description Replaces the current node labels with new label(s). ### Method PUT ### Endpoint /node/labels ### Parameters #### Request Body - **new_labels** (string | list[string]) - A string of space-separated labels or a list of labels to set. - **dryRun** (boolean) - Optional. If true, performs a dry run without applying changes. ### Request Example { "new_labels": "label1 label2", "dryRun": false } ### Response #### Success Response (200) - **message** (string) - Indicates the labels have been updated or the dry run was successful. #### Response Example { "message": "Node labels updated successfully." } ## POST /node/config/load ### Description Loads the config.xml for the node, allowing it to be re-queried without generating new requests. ### Method POST ### Endpoint /node/config/load ### Parameters None ### Response #### Success Response (200) - **message** (string) - Indicates the configuration has been loaded. #### Response Example { "message": "Node configuration loaded." } ## POST /node/config/upload ### Description Uploads the provided config.xml content to the node's config.xml. ### Method POST ### Endpoint /node/config/upload ### Parameters #### Request Body - **config_xml** (string) - The XML content for the node's configuration. ### Request Example { "config_xml": "node1" } ### Response #### Success Response (200) - **message** (string) - Indicates the configuration XML has been uploaded. #### Response Example { "message": "Configuration XML uploaded successfully." } ## POST /node/config/element ### Description Sets a simple configuration element for the node. ### Method POST ### Endpoint /node/config/element ### Parameters #### Request Body - **el_name** (string) - The name of the configuration element to set. - **value** (string) - The value to set for the configuration element. ### Request Example { "el_name": "description", "value": "A test node" } ### Response #### Success Response (200) - **message** (string) - Indicates the configuration element has been set. #### Response Example { "message": "Configuration element 'description' set successfully." } ## PUT /node/config/num_executors ### Description Sets the number of executors for the node. Warning: Setting the number of executors on the master node will erase all other settings. ### Method PUT ### Endpoint /node/config/num_executors ### Parameters #### Request Body - **value** (integer | string) - The number of executors to set. ### Request Example { "value": 5 } ### Response #### Success Response (200) - **message** (string) - Indicates the number of executors has been set. #### Response Example { "message": "Number of executors set successfully." } ## PUT /node/config/offline_reason ### Description Updates the offline reason for a temporarily offline cluster. ### Method PUT ### Endpoint /node/config/offline_reason ### Parameters #### Request Body - **reason** (string) - The new reason for the node being offline. ### Request Example { "reason": "Undergoing scheduled maintenance" } ### Response #### Success Response (200) - **message** (string) - Indicates the offline reason has been updated. #### Response Example { "message": "Offline reason updated successfully." } ``` -------------------------------- ### GET /get_rename_url Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/submodules/mutable_jenkins.md Retrieves the URL endpoint required to perform a rename operation on a mutable Jenkins object. ```APIDOC ## GET /get_rename_url ### Description Returns the specific URL path used to rename the current mutable Jenkins object. ### Method GET ### Endpoint /get_rename_url ### Response #### Success Response (200) - **url** (string) - The full URL string for the rename action. #### Response Example { "url": "http://jenkins-server/job/example-job/confirmRename" } ``` -------------------------------- ### GET /get_delete_url Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/submodules/mutable_jenkins.md Retrieves the URL endpoint required to perform a delete operation on a mutable Jenkins object. ```APIDOC ## GET /get_delete_url ### Description Returns the specific URL path used to delete the current mutable Jenkins object. ### Method GET ### Endpoint /get_delete_url ### Response #### Success Response (200) - **url** (string) - The full URL string for the delete action. #### Response Example { "url": "http://jenkins-server/job/example-job/doDelete" } ``` -------------------------------- ### GET Job Parameters Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/submodules/jobs.md Methods to inspect and list parameters configured for a specific Jenkins job. ```APIDOC ## GET /job/params ### Description Retrieves the parameter definitions or a list of parameter names for a job. ### Method GET ### Response #### Success Response (200) - **params** (dict) - Dictionary containing parameter metadata including type, description, and default values. ``` -------------------------------- ### GET Build Status Methods Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/submodules/jobs.md Methods to retrieve build numbers and objects for various build states. ```APIDOC ## GET /job/build-status ### Description Retrieves numerical IDs or objects for specific build types such as last completed, failed, good, or stable builds. ### Method GET ### Response #### Success Response (200) - **build_number** (int) - The numerical ID of the requested build type. ``` -------------------------------- ### Run JenkinsAPI Test Suite Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/getting_started.md Commands to run the JenkinsAPI test suite. It shows how to execute tests with coverage reporting, both with and without a virtual environment. ```bash uv sync uv run pytest -sv --cov=jenkinsapi --cov-report=term-missing --cov-report=xml jenkinsapi_tests ``` ```bash uv venv uv python install uv run pytest -sv --cov=jenkinsapi --cov-report=term-missing --cov-report=xml jenkinsapi_tests ``` -------------------------------- ### Trigger and Monitor Jenkins Builds Source: https://context7.com/pycontribs/jenkinsapi/llms.txt Demonstrates how to trigger builds with parameters and monitor their status. It covers both non-blocking execution and blocking calls that wait for completion. ```python from jenkinsapi.jenkins import Jenkins jenkins = Jenkins("http://localhost:8080") job = jenkins["my-parameterized-job"] # Simple build (non-blocking) jenkins.build_job("my-job") # Build with parameters (non-blocking) params = {"VERSION": "1.2.3", "ENVIRONMENT": "staging"} jenkins.build_job("my-parameterized-job", params) # Build and get QueueItem for tracking qi = job.invoke(build_params=params) print(f"Queue ID: {qi.queue_id}") # Block until build completes qi = job.invoke(build_params=params, block=True, delay=5) build = qi.get_build() print(f"Build result: {build.get_status()}") ``` -------------------------------- ### Get Job Artifacts (Python) Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/submodules/api.md Retrieves all artifacts associated with a specific build of a Jenkins job. Requires Jenkins URL, job name, build number, and optional authentication credentials. ```python from jenkinsapi.api import get_artifacts j নিরাপত্তা_url = "http://your-jenkins-server.com" job_name = "my_build_job" build_number = 150 artifacts = get_artifacts(jenkins_url, job_name, build_number, username="user", password="pass") for artifact in artifacts: print(artifact.path) ``` -------------------------------- ### Manage Jenkins Views Source: https://context7.com/pycontribs/jenkinsapi/llms.txt Demonstrates how to interact with Jenkins views using the Python library. It shows how to list all available views in a Jenkins instance. ```python from jenkinsapi.jenkins import Jenkins from jenkinsapi.views import Views jenkins = Jenkins("http://localhost:8080") # List all views for view_name in jenkins.views.keys(): print(view_name) ``` -------------------------------- ### Get View from URL (Python) Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/submodules/api.md A factory method to retrieve a Jenkins view object using its URL. This function is a general-purpose way to access Jenkins views. Requires the view URL and optional authentication. ```python from jenkinsapi.api import get_view_from_url view_url = "http://your-jenkins-server.com/view/All/" view = get_view_from_url(view_url) print(f"View jobs: {view.get_jobs()}") ``` -------------------------------- ### Implement resource selection strategies Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/submodules/lockable_resources.md Shows the base ResourceSelector class and its implementations for selecting resources by label, specific name, or a list of names. ```python class ResourceLabelSelector(ResourceSelector): def select(self, lockable_resources): # Logic to select resources by label pass class ResourceNameListSelector(ResourceSelector): def select(self, lockable_resources): # Logic to select from a list of names pass class ResourceNameSelector(ResourceSelector): def select(self, lockable_resources): # Logic to select a single resource by name pass ``` -------------------------------- ### Get Nested View from URL (Python) Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/submodules/api.md Retrieves a Jenkins view object from a provided URL, specifically designed to handle nested views. Requires the full URL of the view and optional authentication credentials. ```python from jenkinsapi.api import get_nested_view_from_url view_url = "http://your-jenkins-server.com/view/Nested/view/SubView/" view = get_nested_view_from_url(view_url, username="user", password="pass") print(f"View name: {view.name}") ``` -------------------------------- ### Get SCM Info from Latest Good Build Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/getting_started.md Retrieves the Source Control Management (SCM) revision information from the last successful build of a Jenkins job. This is useful for triggering release processes based on build versions. ```python from jenkinsapi.jenkins import Jenkins def getSCMInfroFromLatestGoodBuild(url, jobName, username=None, password=None): J = Jenkins(url, username, password) job = J[jobName] lgb = job.get_last_good_build() return lgb.get_revision() if __name__ == '__main__': print getSCMInfroFromLatestGoodBuild('http://localhost:8080', 'fooJob') ``` -------------------------------- ### Build Status and Information Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/submodules/build.md Methods to query the current state, result, and configuration of a Jenkins build. ```APIDOC ## GET /build/status ### Description Retrieves the status and metadata of a specific build. ### Method GET ### Parameters #### Query Parameters - **interval** (int) - Optional - Interval for log streaming in seconds. ### Response #### Success Response (200) - **is_good** (bool) - True if the build was successful. - **is_running** (bool) - True if the build is currently executing. - **has_resultset** (bool) - True if a result set is available. - **is_kept_forever** (bool) - True if the build is marked to be kept forever. - **name** (str) - The name of the build. ### Response Example { "is_good": true, "is_running": false, "has_resultset": true, "is_kept_forever": false, "name": "build-123" } ``` -------------------------------- ### Get Specific Build Information (Python) Source: https://github.com/pycontribs/jenkinsapi/blob/master/doc/submodules/api.md Fetches details for a specific build of a Jenkins job, including test results. Requires Jenkins URL, job name, and build number. Optional authentication parameters can be provided. ```python from jenkinsapi.api import get_build j নিরাপত্তা_url = "http://your-jenkins-server.com" job_name = "my_test_job" build_number = 75 build_info = get_build(jenkins_url, job_name, build_number) print(f"Build {build_number} status: {build_info.get_status()}") ```