jenkinsapi

repository·master·Indexed 21 days ago

https://github.com/pycontribs/jenkinsapi

A Python API for accessing resources on a Jenkins continuous-integration server. The library wraps the Jenkins REST API into Python objects to automate tasks such as job management, pipeline control, artifact management, credential handling, node (slave) configuration, and view management. Version 0.3.20.

Tokens
36.1K
Snippets
115
Records
146
Agent score
75%

What's inside jenkinsapi

  1. Authenticate with Jenkins using username, password, or API token

    master

    When connecting to a Jenkins instance that has authentication enabled, provide the username and password (or an API token) to the Jenkins constructor.

    Tip: It is recommended to use an API Token instead of a password. You can generate an API token in Jenkins under Configure > API Token in your user profile page.

    from jenkinsapi.jenkins import Jenkins
    
    # Using username and password/API token
    J = Jenkins('http://localhost:8080', username='your_user', password='your_password_or_token')
  2. Manage views using the NestedViews Jenkins plugin

    master

    If the NestedViews plugin is installed on your Jenkins server, you can manage hierarchical views using the jenkins.views attribute.

    Key operations include:

    • Creating a Nested View: Use jenkins.views.create("ViewName", Views.NESTED_VIEW).
    • Creating a Sub-view: Use top_view.views.create("SubView") or assign a job name directly to a view key: top_view.views["SubView"] = job_name.
    • Deleting a View: Use the del keyword on the view dictionary, e.g., del top_view.views["SubView"] or del jenkins.views["TopView"].
    import logging
    from pathlib import Path
    from jenkinsapi.views import Views
    from jenkinsapi.jenkins import Jenkins
    
    # Setup
    jenkins_url = "http://127.0.0.1:8080/"
    jenkins = Jenkins(jenkins_url)
    job_name = "foo_job2"
    
    # Create a Nested View
    top_view = jenkins.views.create("TopView", Views.NESTED_VIEW)
    
    # Create a sub-view inside the nested view
    sub_view = top_view.views.create("SubView")
    
    # Alternatively, create a sub-view containing a specific job
    top_view.views["SubView"] = job_name
    
    # Deleting views
    del top_view.views["SubView"]
    del jenkins.views["TopView"]
    
    # Cleanup job
    jenkins.delete_job(job_name)
  3. Authenticate using Crumbs

    master

    When your Jenkins server requires CSRF protection (Crumb issuer), initialize the Jenkins object with use_crumb=True. You must also provide valid username and password credentials.

    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)
  4. Install jenkinsapi via pip

    master

    You can install the library using pip.

    Important Jenkins Configuration Requirements:

    • CSRF Protection: In Jenkins versions > 1.518, you must disable "Prevent Cross Site Request Forgery exploits" for the REST interface to work.
    • Jenkins Location: Ensure the "Jenkins Location" is correctly configured in the Jenkins general settings, otherwise the REST web-interface may not function correctly.
    pip install jenkinsapi
  5. Configure logging for JenkinsAPI

    master

    JenkinsAPI emits request/response debug logs when enabled. You can enable logging in two ways:

    1. Set the JENKINSAPI_LOG_LEVEL environment variable to DEBUG.
    2. Use the configure_logging helper function within your Python code.

    Note that the log level can be set to values like DEBUG or INFO.

    export JENKINSAPI_LOG_LEVEL=DEBUG
    from jenkinsapi.utils.logging import configure_logging
    
    configure_logging("INFO")
  6. Overview of JenkinsAPI capabilities

    master

    JenkinsAPI is a Python wrapper around the Jenkins REST interface. It allows you to perform Jenkins-oriented tasks using conventional Python objects instead of raw REST calls.

    Key capabilities include:

    • Querying test results of completed builds.
    • Retrieving objects representing the latest builds of a job.
    • Searching for artifacts using simple criteria.
    • Blocking execution until jobs are complete.
    • Installing artifacts to custom directory structures.
    • Supporting username/password authentication.
    • Searching for builds by Subversion revision.
    • Adding, removing, and querying Jenkins slaves (nodes).
  7. Check fingerprint validity and handle unknown status

    master

    The valid() method determines if a fingerprint is recognized by Jenkins. It handles the distinction between a definitively invalid fingerprint and one that is "unknown."

    • Positive Validity: The fingerprint is known to the server. valid() returns True and self.unknown is False.
    • Negative Validity: The fingerprint is definitively not valid. valid() returns False.
    • Unknown Status: If the server returns a 404 error, the library treats this as an "unknown" state rather than a definitive failure. In this case, valid() returns True, but self.unknown is set to True. This occurs when fingerprints might not be enabled on the Jenkins server.

    Note: If valid() returns True but self.unknown is True, the artifact might still exist, but its validity cannot be confirmed by the server.

  8. Supported Jenkins credential types

    master

    When working with the Credentials or CredentialsById classes, the library automatically maps Jenkins credential data to specific Python classes. Supported types include:

    • UsernamePasswordCredential: For 'Username with password' types.
    • SSHKeyCredential: For 'SSH Username with private key' types.
    • SecretTextCredential: For 'Secret text' types.
    • FileCredentials: For 'Secret file' types or credentials containing file/byte data.
    • DockerServerCredentials: For 'Docker Host Certificate Authentication', 'X.509 Client Certificate', or credentials containing client keys/certificates.
    • Credential: A generic fallback for other types.
  9. Use the Jobs class to manage Jenkins jobs

    master

    The Jobs class acts as a container-like interface for all jobs on a Jenkins server. It behaves similarly to a Python dictionary where keys are job names (strings) and values are jenkinsapi.Job objects. You can use it to access, create, delete, and iterate over jobs.

    Key behaviors:

    • Accessing jobs: Use jobs['job_name'] to retrieve a Job object.
    • Creating jobs: Use jobs['new_job_name'] = config_xml or the .create() method.
    • Deleting jobs: Use del jobs['job_name'].
    • Iteration: Use .keys(), .itervalues(), or .iteritems() to loop through jobs.
    from jenkinsapi import Jenkins
    
    api = Jenkins('http://localhost:8080/')
    jobs = api.jobs
    
    # Access a job
    my_job = jobs['my_job_name']
    
    # Create a job with XML config
    config_xml = "<job>...</job>"
    new_job = jobs['my_new_job'] = config_xml
    
    # Delete a job
    del jobs['my_job_name']
  10. Manage Jenkins Nodes with the Node class

    master

    The Node class represents a Jenkins agent/node (slave) attached to the master instance. It allows you to inspect node status, manage connectivity, modify configurations (like labels and executors), and retrieve system monitor data (like memory or disk space).

    from jenkinsapi.jenkins import Jenkins
    from jenkinsapi.node import Node
    
    jenkins = Jenkins(url='http://jenkins-server:8080', username='admin', password='password')
    # Access an existing node by name
    node = jenkins.get_node('my-agent-name')
    
    if node.is_online():
        print(f"Node {node.name} is online and idle: {node.is_idle()}")