### POST /installNecessaryPlugins
Source: https://api4jenkins.readthedocs.io/en/latest/_modules/api4jenkins/plugin.html
Installs a list of plugins by name. Optionally blocks until installation is complete.
```APIDOC
## POST /installNecessaryPlugins
### Description
Installs one or more plugins. If a version is not specified, it defaults to @latest.
### Method
POST
### Endpoint
/installNecessaryPlugins
### Request Body
- **plugin** (string) - Required - The name of the plugin to install, optionally followed by @version.
```
--------------------------------
### Install api4jenkins from source
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/install.rst.txt
Clone the repository and install the package locally from the source code.
```bash
$ git clone https://github.com/joelee2012/api4jenkins
$ cd api4jenkins
$ python -m pip install .
```
--------------------------------
### Execute Python Script to Install Plugins
Source: https://api4jenkins.readthedocs.io/en/latest/user/example.html
Command to run the `install_plugins.py` script, passing plugin names as command-line arguments. This initiates the plugin installation process defined in the script.
```bash
python3 install_plugins.py plugin1 plugin2
```
--------------------------------
### Install Plugins
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Install one or more plugins. The `block` parameter determines if the operation waits for completion.
```python
>>> j.plugins.install('cloudbees-folder', 'credentials', block=True)
```
--------------------------------
### GET /installStatus
Source: https://api4jenkins.readthedocs.io/en/latest/_modules/api4jenkins/plugin.html
Retrieves the installation status of pending plugin jobs.
```APIDOC
## GET /installStatus
### Description
Checks the status of current plugin installation jobs.
### Method
GET
### Endpoint
/installStatus
### Response
#### Success Response (200)
- **data** (object) - Contains a list of jobs and their respective installStatus.
```
--------------------------------
### Create and Build Jenkins Job (Async)
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/index.rst.txt
This example shows how to perform the same job creation and building tasks as the sync example, but using the asynchronous API. This is suitable for non-blocking operations in Python applications.
```python
import asyncio
import time
from api4jenkins import AsyncJenkins
async def main():
client = AsyncJenkins('http://127.0.0.1:8080/', auth=('admin', 'admin'))
print(await client.version)
xml = """
echo $JENKINS_VERSION
"""
await client.create_job('job', xml)
item = await client.build_job('job')
while not await item.get_build():
time.sleep(1)
build = await item.get_build()
async for line in build.progressive_output():
print(line)
print(await build.building)
print(await build.result)
asyncio.run(main())
```
--------------------------------
### Get Build Parameters and Causes
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Retrieves the parameters used to start a build and the causes that triggered the build.
```python
paramters = build.get_parameters()
```
```python
causes = build.get_causes()
```
--------------------------------
### Install api4jenkins via pip
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/install.rst.txt
The recommended method for installing the library using the Python package manager.
```bash
$ python -m pip install api4jenkins
```
--------------------------------
### Iterate and Print Jenkins Plugins
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Iterates through all installed Jenkins plugins and prints their representation. No specific setup is required if the Jenkins object `j` is already initialized.
```python
for plugin in j.plugins:
print(plugin)
```
--------------------------------
### Plugin Management
Source: https://api4jenkins.readthedocs.io/en/latest/genindex.html
Handles plugin installation, uninstallation, and update center access.
```APIDOC
## Plugin Management
### Description
Provides functionalities for managing Jenkins plugins.
### Methods
- `uninstall()`: Uninstalls a plugin.
### Properties
- `update_center`: Accesses the plugin update center.
### Classes
- `api4jenkins.plugin.Plugin`
- `api4jenkins.plugin.PluginsManager`
- `api4jenkins.plugin.AsyncPlugin`
- `api4jenkins.plugin.AsyncPluginsManager`
- `api4jenkins.plugin.UpdateCenter`
```
--------------------------------
### Start a Build
Source: https://api4jenkins.readthedocs.io/en/latest/user/example.html
Initiates a build for a Jenkins project. Returns a QueueItem object that can be used to track the build.
```python
>>> item = job.build()
>>> import time
>>> while not item.get_build():
... time.sleep(1)
>>> build = item.get_build()
>>> print(build)
>>> for line in build.progressive_output():
... print(line)
```
--------------------------------
### Install Jenkins Plugins with Python Script
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
A Python script to install Jenkins plugins. It requires Jenkins URL, username, and password. It can optionally set an HTTPS proxy and handles Jenkins restarts if required after installation. The script installs plugins specified as command-line arguments.
```python
#!python
URL = 'http://localhost:8080'
USER = 'admin'
PASSWORD = '1234'
def install_plugins(*names):
import re
import time
import os
from api4jenkins import Jenkins
jenkins = Jenkins(URL, auth=(USER, PASSWORD))
if os.getenv('HTTPS_PROXY'):
matcher = re.match(r'(?P.*):(?P\d+)$', os.getenv('HTTPS_PROXY'))
jenkins.plugins.set_proxy(matcher['ip'], port=matcher['port'])
jenkins.plugins.check_updates_server()
jenkins.plugins.install(*names, block=True)
if jenkins.plugins.restart_required:
jenkins.system.safe_restart()
while not jenkins.exists():
time.sleep(2)
for name in names:
if not jenkins.plugins.get(name):
raise RuntimeError(f'{name} was not installed successful')
if __name__ == '__main__':
import logging
import sys
logging.basicConfig(level=logging.DEBUG)
install_plugins(*sys.argv[1:])
```
--------------------------------
### Plugin Management Methods
Source: https://api4jenkins.readthedocs.io/en/latest/genindex.html
Methods for installing and managing plugins.
```APIDOC
## install() /api/plugins/install
### Description
Installs plugins in Jenkins.
### Method
Not specified (likely POST or PUT)
### Endpoint
/api/plugins/install
### Parameters
None specified
### Request Example
None specified
### Response
None specified
```
--------------------------------
### Check Plugin Installation Status
Source: https://api4jenkins.readthedocs.io/en/latest/user/example.html
Check if plugin installation is complete or if a Jenkins restart is required. `installation_done` is a boolean, and `restart_required` indicates if a restart is needed.
```python
>>> j.plugins.installation_done
```
```python
>>> j.plugins.restart_required
```
--------------------------------
### Iterate Through Installed Plugins
Source: https://api4jenkins.readthedocs.io/en/latest/user/example.html
Loop through all currently installed plugins on Jenkins. Each `plugin` object can be further inspected or manipulated.
```python
>>> for plugin in j.plugins:
... print(plugin)
```
--------------------------------
### Build Jenkins Project with Parameters
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Starts a build for a Jenkins project, passing custom parameters as key-value arguments.
```python
item = job.build(arg1='string1', arg2='string2')
```
--------------------------------
### Configure View
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Use this to get or update the configuration of an existing view. Pass new XML to update.
```python
>>> print(view.configure())
>>> view.configure(new_xml)
```
--------------------------------
### Get and Set Build Description
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Retrieves the current description of a build and allows setting a new description.
```python
build.description
```
```python
build.set_description('new description')
```
--------------------------------
### Build Jenkins Project
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Starts a new build for a Jenkins project. Returns a `QueueItem` object that can be used to track the build's progress.
```python
item = job.build()
import time
while not item.get_build():
time.sleep(1)
build = item.get_build()
print(build)
```
--------------------------------
### Build Navigation API
Source: https://api4jenkins.readthedocs.io/en/latest/_modules/api4jenkins/build.html
APIs for navigating between builds, such as getting the next or previous build.
```APIDOC
## GET /nextBuild
### Description
Retrieves information about the next build in the sequence.
### Method
GET
### Endpoint
/nextBuild
### Parameters
#### Query Parameters
- **tree** (string) - Optional - Specifies the fields to retrieve, e.g., `tree=nextBuild[url]`.
### Request Example
```
GET /job/my-job/1/api/json?tree=nextBuild[url]
```
### Response
#### Success Response (200)
- **nextBuild** (object) - An object containing information about the next build, typically including its URL.
- **url** (string) - The URL of the next build.
#### Response Example
```json
{
"_class": "org.jenkinsci.plugins.workflow.job.WorkflowRun",
"nextBuild": {
"number": 2,
"url": "http://localhost:8080/job/my-job/2/"
}
}
```
## GET /previousBuild
### Description
Retrieves information about the previous build in the sequence.
### Method
GET
### Endpoint
/previousBuild
### Parameters
#### Query Parameters
- **tree** (string) - Optional - Specifies the fields to retrieve, e.g., `tree=previousBuild[url]`.
### Request Example
```
GET /job/my-job/2/api/json?tree=previousBuild[url]
```
### Response
#### Success Response (200)
- **previousBuild** (object) - An object containing information about the previous build, typically including its URL.
- **url** (string) - The URL of the previous build.
#### Response Example
```json
{
"_class": "org.jenkinsci.plugins.workflow.job.WorkflowRun",
"previousBuild": {
"number": 1,
"url": "http://localhost:8080/job/my-job/1/"
}
}
```
```
--------------------------------
### get()
Source: https://api4jenkins.readthedocs.io/en/latest/genindex.html
Retrieves various resources including credentials, jobs, nodes, plugins, queues, reports, users, and views.
```APIDOC
## get()
### Description
Generic retrieval method used across multiple modules to fetch specific resource instances or collections.
### Method
Method call on various classes including api4jenkins.credential, api4jenkins.job, api4jenkins.node, api4jenkins.plugin, api4jenkins.queue, api4jenkins.report, api4jenkins.user, and api4jenkins.view.
```
--------------------------------
### Build with Delay and Token
Source: https://api4jenkins.readthedocs.io/en/latest/user/example.html
Starts a Jenkins build with a specified delay and an optional token for identification.
```python
>>> item = job.build(delay='30sec', token='abc')
```
--------------------------------
### Configure Credential
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Use this to get or update the configuration of an existing credential. Pass new XML to update.
```python
>>> print(credential.configure())
>>> credential.configure(new_xml)
```
--------------------------------
### AsyncPluginsManager Class Methods
Source: https://api4jenkins.readthedocs.io/en/latest/_modules/api4jenkins/plugin.html
Methods for interacting with Jenkins plugins asynchronously, including retrieval, installation, and configuration.
```python
class AsyncPluginsManager(AsyncItem):
[docs]
async def get(self, name):
data = await self.api_json(tree='plugins[shortName]')
for plugin in data['plugins']:
if plugin['shortName'] == name:
return AsyncPlugin(self.jenkins, f'{self.url}plugin/{name}/')
return None
[docs]
async def install(self, *names, block=False):
plugin_xml = ET.Element('jenkins')
for name in names:
if '@' not in name:
name += '@latest'
ET.SubElement(plugin_xml, 'install', {'plugin': name})
await self.handle_req('POST', 'installNecessaryPlugins',
headers=self.headers,
content=ET.tostring(plugin_xml))
while block and not await self.installation_done:
time.sleep(2)
[docs]
async def uninstall(self, *names):
for name in names:
await self.handle_req('POST', f'plugin/{name}/doUninstall')
[docs]
async def set_site(self, url):
await self.handle_req('POST', 'siteConfigure', params={'site': url})
await self.check_updates_server()
[docs]
async def check_updates_server(self):
await self.handle_req('POST', 'checkUpdatesServer')
@property
def update_center(self):
return AsyncUpdateCenter(self.jenkins, f'{self.jenkins.url}updateCenter/')
@property
def site(self):
return self.update_center.site
@property
def restart_required(self):
return self.update_center.restart_required
@property
def installation_done(self):
return self.update_center.installation_done
[docs]
async def set_proxy(self, name, port, *, username='',
password='', no_proxy='', test_url=''):
data = {'name': name, 'port': port, 'userName': username,
'password': password, 'noProxyHost': no_proxy,
'testUrl': test_url}
await self.handle_req('POST', 'proxyConfigure', data={
'json': json.dumps(data)})
async def __aiter__(self):
data = await self.api_json(tree='plugins[shortName]')
for plugin in data['plugins']:
yield AsyncPlugin(self.jenkins,
f'{self.url}plugin/{plugin["shortName"]}/')
```
--------------------------------
### Create and Get Credential
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Use this to create or retrieve a username/password credential within a specific domain. Requires XML configuration for the credential.
```python
>>> xml = '''
... user-id
... user-name
... user-password
... user id for testing
... '''
>>> domain.create(xml)
>>> credential = domain.get('user-id')
```
--------------------------------
### Get Build Console Output
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Retrieves the console output of a build line by line.
```python
for line in build.console_text():
print(line)
```
--------------------------------
### Create and Get Domain
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Use this to create or retrieve a credential domain within a Jenkins folder. Requires XML configuration for the domain.
```python
>>> xml = '''
... testing
... Credentials for use against the *.test.example.com hosts
...
...
... *.test.example.com
...
...
...
... '''
>>> folder.credentials.create(xml)
>>> domain = folder.credentials.get('testing')
```
--------------------------------
### Get Build Project, Previous, or Next Build
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Retrieves the associated project for a build, or the previous and next builds in the sequence.
```python
job = build.project
```
```python
pre_build = build.get_previous_build()
```
```python
next_build = build.get_next_build()
```
--------------------------------
### Create and Build Jenkins Job (Sync)
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/index.rst.txt
This example demonstrates how to create a Jenkins job from XML, build it, and monitor its progress using the synchronous API. Ensure you have a Jenkins instance running and accessible.
```python
>>> from api4jenkins import Jenkins
>>> client = Jenkins('http://127.0.0.1:8080/', auth=('admin', 'admin'))
>>> client.version
'2.176.2'
>>> xml = """
...
...
...
... echo $JENKINS_VERSION
...
...
... """
>>> client.create_job('path/to/job', xml)
>>> import time
>>> item = client.build_job('path/to/job')
>>> while not item.get_build():
... time.sleep(1)
>>> build = item.get_build()
>>> for line in build.progressive_output():
... print(line)
...
Started by user admin
Running as SYSTEM
Building in workspace /var/jenkins_home/workspace/freestylejob
[freestylejob] $ /bin/sh -xe /tmp/jenkins2989549474028065940.sh
+ echo $JENKINS_VERSION
2.176.2
Finished: SUCCESS
>>> build.building
False
>>> build.result
'SUCCESS'
```
--------------------------------
### Plugin Management API
Source: https://api4jenkins.readthedocs.io/en/latest/user/example.html
APIs for managing Jenkins plugins, including getting, installing, uninstalling, and updating plugin sites.
```APIDOC
## Plugin Management API
### Description
APIs for managing Jenkins plugins, including getting, installing, uninstalling, and updating plugin sites.
### Get Plugin by Name
#### Method
GET (Implicit)
#### Endpoint
`/jenkins/plugins/{name}` (Conceptual)
### Install Plugin
#### Method
POST (Conceptual)
#### Endpoint
`/jenkins/plugins/install` (Conceptual)
#### Parameters
- **names** (string array) - Required - Names of plugins to install.
- **block** (boolean) - Optional - If true, the operation will block until installation is complete.
### Uninstall Plugin
#### Method
POST (Conceptual)
#### Endpoint
`/jenkins/plugins/uninstall` (Conceptual)
#### Parameters
- **names** (string array) - Required - Names of plugins to uninstall.
### Set Plugin Update Site
#### Method
POST (Conceptual)
#### Endpoint
`/jenkins/plugins/set-site` (Conceptual)
#### Parameters
- **url** (string) - Required - The URL of the update site.
### Set Proxy for Update Site
#### Method
POST (Conceptual)
#### Endpoint
`/jenkins/plugins/set-proxy` (Conceptual)
#### Parameters
- **ip** (string) - Required - The IP address of the proxy.
- **port** (string) - Required - The port of the proxy.
### Check for Updates
#### Method
GET (Conceptual)
#### Endpoint
`/jenkins/plugins/check-updates` (Conceptual)
### Iterate Plugins
#### Method
GET (Conceptual)
#### Endpoint
`/jenkins/plugins` (Conceptual)
### Plugin Installation Status
#### Properties
- **installation_done** (boolean) - Indicates if plugin installation is completed.
- **restart_required** (boolean) - Indicates if a restart is required after plugin changes.
### Uninstall Plugin (Instance Method)
#### Method
POST (Conceptual)
#### Endpoint
`/jenkins/plugins/{name}/uninstall` (Conceptual)
### Check if Plugin Exists
#### Method
GET (Conceptual)
#### Endpoint
`/jenkins/plugins/{name}/exists` (Conceptual)
#### Response
- **exists** (boolean) - True if the plugin exists, False otherwise.
### Example: Full Plugin Installation Script
```python
URL = 'http://localhost:8080'
USER = 'admin'
PASSWORD = '1234'
def install_plugins(*names):
import re
import time
import os
from api4jenkins import Jenkins
jenkins = Jenkins(URL, auth=(USER, PASSWORD))
if os.getenv('HTTPS_PROXY'):
matcher = re.match(r'(?P.*):(?P\d+)$', os.getenv('HTTPS_PROXY'))
jenkins.plugins.set_proxy(matcher['ip'], port=matcher['port'])
jenkins.plugins.check_updates_server()
jenkins.plugins.install(*names, block=True)
if jenkins.plugins.restart_required:
jenkins.system.safe_restart()
while not jenkins.exists():
time.sleep(2)
for name in names:
if not jenkins.plugins.get(name):
raise RuntimeError(f'{name} was not installed successful')
if __name__ == '__main__':
import logging
import sys
logging.basicConfig(level=logging.DEBUG)
install_plugins(*sys.argv[1:])
```
### Example: Calling the Installation Script
```bash
python3 install_plugins.py plugin1 plugin2
```
```
--------------------------------
### Iterate Jenkins Jobs
Source: https://api4jenkins.readthedocs.io/en/latest/user/api.html
Demonstrates how to initialize a Jenkins client and iterate through available jobs.
```python
>>> from api4jenkins import Jenkins
>>> j = Jenkins('http://127.0.0.1:8080/', auth=('admin', 'admin'))
>>> for job in j.iter():
... print(job)
...
```
--------------------------------
### Plugin Installation Status
Source: https://api4jenkins.readthedocs.io/en/latest/genindex.html
Properties related to the status of plugin installations.
```APIDOC
## installation_done (property)
### Description
Indicates whether plugin installation is complete. This property is available for plugin managers and update centers.
### Method
Not specified (likely GET)
### Endpoint
Not specified (property access)
### Parameters
None specified
### Request Example
None specified
### Response
Boolean indicating completion status.
```
--------------------------------
### Jenkins Client Initialization
Source: https://api4jenkins.readthedocs.io/en/latest/user/api.html
How to initialize the Jenkins client to connect to a server.
```APIDOC
## Jenkins Constructor
### Description
Constructs a Jenkins client instance.
### Parameters
#### Arguments
- **url** (str) - Required - URL of the Jenkins server.
- **auth** (tuple) - Optional - Auth tuple to enable Basic/Digest/Custom HTTP Auth.
- **kwargs** (dict) - Optional - Additional arguments passed to httpx.Client.
```
--------------------------------
### Get Special Builds
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Shortcut methods to retrieve specific types of builds, such as the first, last, completed, failed, or successful build.
```python
job.get_first_build()
```
```python
job.get_last_build()
```
```python
job.get_last_completed_build()
```
```python
job.get_last_failed_build()
```
```python
job.get_last_stable_build()
```
```python
job.get_last_successful_build()
```
```python
job.get_last_unstable_build()
```
```python
job.get_last_unsuccessful_build()
```
--------------------------------
### Create a Jenkins Folder
Source: https://api4jenkins.readthedocs.io/en/latest/user/example.html
Initializes an empty folder in Jenkins using an XML configuration string.
```python
>>> xml = '''
...
...
...
...
...
...
... '''
>>> j.create_job('folder name', xml)
```
--------------------------------
### Initialize Jenkins Client
Source: https://api4jenkins.readthedocs.io/en/latest/_modules/api4jenkins.html
Instantiate the Jenkins client with the server URL and optional authentication. Additional keyword arguments are passed to httpx.Client.
```python
from api4jenkins import Jenkins
j = Jenkins('http://127.0.0.1:8080/', auth=('admin', 'admin'))
print(j)
print(j.version)
```
--------------------------------
### Check Jenkins Plugin Installation Status
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Checks if plugin installation is complete or if a Jenkins restart is required. Assumes the Jenkins object `j` is initialized.
```python
j.plugins.installation_done
```
```python
j.plugins.restart_required
```
--------------------------------
### Manage Project Configuration and Parameters
Source: https://api4jenkins.readthedocs.io/en/latest/_modules/api4jenkins/job.html
Methods to set the next build number and retrieve parameter definitions from project properties.
```python
def set_next_build_number(self, number):
self.handle_req('POST', 'nextbuildnumber/submit',
params={'nextBuildNumber': number})
```
```python
def get_parameters(self):
params = []
for p in self.api_json()['property']:
if 'parameterDefinitions' in p:
params = p['parameterDefinitions']
return params
```
--------------------------------
### Async Get Item Implementation
Source: https://api4jenkins.readthedocs.io/en/latest/_modules/api4jenkins/item.html
Implements asynchronous item retrieval using `__getitem__`. It attempts to use a `get` method if available, otherwise raises a TypeError.
```python
async def __getitem__(self, name):
if hasattr(self, 'get'):
return await self.get(name)
raise TypeError(f
```
--------------------------------
### POST /create
Source: https://api4jenkins.readthedocs.io/en/latest/genindex.html
Generic creation method for various Jenkins resources.
```APIDOC
## POST /create
### Description
Creates resources such as AsyncCredentials, AsyncDomain, Folders, OrganizationFolders, Nodes, and Views.
### Method
POST
### Endpoint
/create
```
--------------------------------
### Build a Jenkins Job
Source: https://api4jenkins.readthedocs.io/en/latest/_modules/api4jenkins.html
Shows how to trigger a job build and monitor its output using the QueueItem.
```python
>>> from api4jenkins import Jenkins
>>> j = Jenkins('http://127.0.0.1:8080/', auth=('admin', 'admin'))
>>> item = j.build_job('freestylejob')
>>> import time
>>> while not item.get_build():
... time.sleep(1)
>>> build = item.get_build()
>>> print(build)
>>> for line in build.progressive_output():
... print(line)
...
```
--------------------------------
### Get MixIn for Item Iteration
Source: https://api4jenkins.readthedocs.io/en/latest/_modules/api4jenkins/report.html
Provides a 'get' method to find an item by name within an iterable collection of items. Useful for retrieving specific test suites, cases, or coverage metrics.
```python
# encoding: utf-8
from .item import AsyncItem, Item, camel, snake
[docs]
class GetMixIn:
[docs]
def get(self, name):
return next((item for item in self if item.name == name), None)
```
--------------------------------
### Build with Parameters
Source: https://api4jenkins.readthedocs.io/en/latest/user/example.html
Initiates a Jenkins build, passing custom parameters as key-value arguments.
```python
>>> item = job.build(arg1='string1', arg2='string2')
```
--------------------------------
### Synchronous Jenkins Job Creation and Build
Source: https://api4jenkins.readthedocs.io/en/latest/index.html
Use this synchronous example to create a Jenkins job from an XML configuration, trigger a build, and monitor its output until completion. Ensure you have a Jenkins instance running and accessible.
```python
>>> from api4jenkins import Jenkins
>>> client = Jenkins('http://127.0.0.1:8080/', auth=('admin', 'admin'))
>>> client.version
'2.176.2'
>>> xml = """
...
...
...
... echo $JENKINS_VERSION
...
...
... """
>>> client.create_job('path/to/job', xml)
>>> import time
>>> item = client.build_job('path/to/job')
>>> while not item.get_build():
... time.sleep(1)
>>> build = item.get_build()
>>> for line in build.progressive_output():
... print(line)
...
Started by user admin
Running as SYSTEM
Building in workspace /var/jenkins_home/workspace/freestylejob
[freestylejob] $ /bin/sh -xe /tmp/jenkins2989549474028065940.sh
+ echo $JENKINS_VERSION
2.176.2
Finished: SUCCESS
>>> build.building
False
>>> build.result
'SUCCESS'
```
--------------------------------
### GET /api/json
Source: https://api4jenkins.readthedocs.io/en/latest/user/api.html
Retrieves the JSON representation of a view or dashboard.
```APIDOC
## GET /api/json
### Description
Retrieves the JSON representation of the view or dashboard.
### Method
GET
### Parameters
#### Query Parameters
- **tree** (string) - Optional - The tree parameter for Jenkins API.
- **depth** (integer) - Optional - The depth parameter for Jenkins API.
```
--------------------------------
### Get Coverage Report
Source: https://api4jenkins.readthedocs.io/en/latest/user/api.html
Accesses the JaCoCo coverage report for a build.
```APIDOC
## get_coverage_report()
### Description
Access coverage report generated by JaCoCo.
```
--------------------------------
### Get Job Parameters
Source: https://api4jenkins.readthedocs.io/en/latest/user/example.html
Retrieves the parameters defined for a Jenkins job.
```python
>>> parameters = job.get_parameters()
```
--------------------------------
### AsyncGitHubSCMNavigator Methods
Source: https://api4jenkins.readthedocs.io/en/latest/user/api.html
Methods for interacting with AsyncGitHubSCMNavigator objects.
```APIDOC
## AsyncGitHubSCMNavigator Methods
### Description
Provides methods for managing GitHub SCM navigators asynchronously.
### Methods
- `_duplicate(path, recursive=False)`: Duplicates the SCM navigator.
- `_enable()`: Enables the SCM navigator.
- `_exists()`: Checks if the SCM navigator exists.
- `_filter_builds_by_result(result)`: Filters builds by their result.
- `_get(number)`: Retrieves a specific build by its number.
- `_get_parameters()`: Gets the parameters for the SCM navigator.
- `_handle_req(method, entry, **kwargs)`: Handles raw requests.
- `handle_stream(method, entry, **kwargs)`: Handles streaming requests.
- `_iter_all_builds()`: Iterates over all builds.
- `_move(path)`: Moves the SCM navigator to a new path.
- `_rename(name)`: Renames the SCM navigator.
- `_set_description(text)`: Sets the description for the SCM navigator.
- `_set_next_build_number(number)`: Sets the next build number.
- `_configure(xml=None)`: Configures the SCM navigator with XML.
- `_delete()`: Deletes the SCM navigator.
- `_disable()`: Disables the SCM navigator.
- `_api_json(tree='', depth=0)`: Retrieves API JSON data.
- `_build(**params)`: Triggers a build.
### Properties
- `_building`: Boolean indicating if a build is in progress.
- `_dynamic_attrs`: Dynamic attributes of the SCM navigator.
- `_full_display_name`: The full display name.
- `_full_name`: The full name.
- `_name`: The name of the SCM navigator.
- `_parent`: The parent object.
### Request Body Examples
```json
{
"xml": "..."
}
```
### Response Examples
```json
{
"status": "success"
}
```
```
--------------------------------
### Get Plugin by Name
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Retrieve a Jenkins plugin object by its name.
```python
>>> plugin = j.plugins.get('cloudbees-folder')
```
--------------------------------
### GET /job/api/json
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Retrieves the configuration and status attributes of a Jenkins job.
```APIDOC
## GET /job/api/json
### Description
Retrieves the JSON representation of a Jenkins job, including metadata like name, description, and build status.
### Method
GET
### Endpoint
//api/json
### Response
#### Success Response (200)
- **_class** (string) - The Jenkins class type.
- **description** (string) - Job description.
- **displayName** (string) - Display name of the job.
- **buildable** (boolean) - Whether the job can be built.
- **url** (string) - URL of the job.
```
--------------------------------
### Manage Build Artifacts
Source: https://api4jenkins.readthedocs.io/en/latest/user/example.html
Retrieve and save build artifacts or download them as a zip file.
```python
>>> for artifacts in build.get_artifacts():
... if artifacts.name == 'you need':
... artfacts.save('filename')
```
```python
>>> build.save_artifacts('filename.zip')
```
--------------------------------
### Get Job Description
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Retrieves the current description of a Jenkins job.
```python
job.description
```
--------------------------------
### AsyncJenkins class initialization
Source: https://api4jenkins.readthedocs.io/en/latest/_modules/api4jenkins.html
Initializes the AsyncJenkins client with a URL and optional authentication parameters.
```python
[docs]
class AsyncJenkins(AsyncItem, UrlMixIn):
def __init__(self, url, **kwargs):
self.http_client = new_async_http_client(**kwargs)
self._crumb = None
self._async_lock = asyncio.Lock()
self._auth = kwargs.get('auth')
super().__init__(self, url)
self.user = AsyncUser(
self, f'{self.url}user/{self._auth[0]}/') if self._auth else None
```
--------------------------------
### GET /get_pending_input
Source: https://api4jenkins.readthedocs.io/en/latest/user/api.html
Retrieve the current pending input step for a workflow run.
```APIDOC
## GET /get_pending_input
### Description
Get current pending input step.
### Method
GET
### Endpoint
/get_pending_input
```
--------------------------------
### Jenkins Node Creation Parameters
Source: https://api4jenkins.readthedocs.io/en/latest/user/example.html
Example of keyword arguments (`kwargs`) that can be used when creating a new Jenkins node. These parameters define the node's description, executors, remote file system, labels, mode, retention strategy, properties, and launcher.
```json
{
'nodeDescription': '',
'numExecutors': 1,
'remoteFS': '/home/jenkins',
'labelString': '',
'mode': 'NORMAL',
'retentionStrategy': {
'stapler-class': 'hudson.slaves.RetentionStrategy$Always'
},
'nodeProperties': {'stapler-class-bag': 'true'},
'launcher': {'stapler-class': 'hudson.slaves.JNLPLauncher'}
}
```
--------------------------------
### GET /get_coverage_result
Source: https://api4jenkins.readthedocs.io/en/latest/user/api.html
Access the coverage result generated by the Code Coverage API.
```APIDOC
## GET /get_coverage_result
### Description
Access coverage result generated by Code Coverage API.
### Method
GET
### Endpoint
/get_coverage_result
```
--------------------------------
### GET /get_coverage_report
Source: https://api4jenkins.readthedocs.io/en/latest/user/api.html
Access the coverage report generated by JaCoCo for a specific build.
```APIDOC
## GET /get_coverage_report
### Description
Access coverage report generated by JaCoCo.
### Method
GET
### Endpoint
/get_coverage_report
```
--------------------------------
### Initialize Jenkins Object
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Initialize the Jenkins object with the Jenkins URL and authentication credentials. Any parameter supported by httpx.Client can be passed.
```python
from api4jenkins import Jenkins
j = Jenkins('http://127.0.0.1:8080/', auth=('username', 'password or token'))
print(j)
```
--------------------------------
### Get Build Console Output
Source: https://api4jenkins.readthedocs.io/en/latest/user/api.html
Retrieves the console output for an asynchronous build.
```APIDOC
## console_text()
### Description
Access the console output text of the build.
```
--------------------------------
### Create HTTP Clients
Source: https://api4jenkins.readthedocs.io/en/latest/_modules/api4jenkins/http.html
Factory functions to instantiate httpx Client or AsyncClient with pre-configured transport and event hooks.
```python
def new_http_client(**kwargs) -> Client:
trans = _new_transport(HTTPTransport, kwargs)
return Client(
transport=trans,
**kwargs,
event_hooks={'request': [log_request], 'response': [check_response]}
)
```
```python
def new_async_http_client(**kwargs) -> AsyncClient:
trans = _new_transport(AsyncHTTPTransport, kwargs)
return AsyncClient(
transport=trans,
**kwargs,
event_hooks={'request': [async_log_request],
'response': [async_check_response]}
)
```
--------------------------------
### GET /credentials
Source: https://api4jenkins.readthedocs.io/en/latest/genindex.html
Retrieves credentials associated with Jenkins instances, folders, or projects.
```APIDOC
## GET /credentials
### Description
Accesses the credentials property for various Jenkins entities including AsyncJenkins, Jenkins, Folders, and WorkflowMultiBranchProjects.
### Method
GET
### Endpoint
/credentials
```
--------------------------------
### Create System-Based View
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Use this to create a new system-wide view in Jenkins. Requires XML configuration for the view.
```python
>>> j.views.create('test_view', xml)
>>> view = j.views.get('test_view')
```
--------------------------------
### Get Job from View
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Retrieve a specific job by its name from a Jenkins view.
```python
>>> job = view.get('job name')
```
--------------------------------
### Jenkins API - O Section
Source: https://api4jenkins.readthedocs.io/en/latest/genindex.html
Details on entities and classes starting with 'O' in the Jenkins API.
```APIDOC
## O
### Classes
- **OrganizationFolder** (class in api4jenkins.job)
```
--------------------------------
### Get Test Case by Name
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Retrieve a specific test case from a TestSuite by its name.
```python
>>> case = suite.get('case name')
```
--------------------------------
### Get Test Suite by Name
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Retrieve a specific test suite from the TestReport by its name.
```python
>>> suite = tr.get('name of suite')
```
--------------------------------
### Get Build from Queue Item
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Retrieve the Jenkins build associated with a queue item.
```python
>>> build = item.get_build()
```
--------------------------------
### Get Job from Queue Item
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Retrieve the Jenkins job associated with a queue item.
```python
>>> job = item.get_job()
```
--------------------------------
### POST /proxyConfigure
Source: https://api4jenkins.readthedocs.io/en/latest/_modules/api4jenkins/plugin.html
Configures proxy settings for the Jenkins instance.
```APIDOC
## POST /proxyConfigure
### Description
Updates the proxy configuration for Jenkins.
### Method
POST
### Endpoint
/proxyConfigure
### Request Body
- **json** (object) - Required - A JSON string containing name, port, userName, password, noProxyHost, and testUrl.
```
--------------------------------
### BitbucketSCMNavigator API
Source: https://api4jenkins.readthedocs.io/en/latest/user/api.html
Operations for managing BitbucketSCMNavigator configurations in Jenkins.
```APIDOC
## BitbucketSCMNavigator Operations
### Description
Provides methods for interacting with BitbucketSCMNavigator configurations.
### Methods
- `api_json(tree='', depth=0)`: Retrieves API JSON data.
- `build(**params)`: Initiates a build.
- `configure(xml=None)`: Configures the navigator.
- `delete()`: Deletes the navigator configuration.
- `disable()`: Disables the navigator.
- `duplicate(path, recursive=False)`: Duplicates the navigator configuration.
- `enable()`: Enables the navigator.
- `exists()`: Checks if the navigator configuration exists.
- `filter_builds_by_result(*, result)`: Filters builds by result.
- `get(number)`: Retrieves a specific build.
- `get_parameters()`: Retrieves build parameters.
- `handle_req(method, entry, **kwargs)`: Handles API requests.
- `handle_stream(method, entry, **kwargs)`: Handles streaming API responses.
- `iter()`: Iterates over items.
- `iter_all_builds()`: Iterates over all builds.
- `move(path)`: Moves the navigator configuration.
- `rename(name)`: Renames the navigator configuration.
- `set_description(text)`: Sets the description.
- `set_next_build_number(number)`: Sets the next build number.
### Properties
- `_building`: Boolean indicating if a build is in progress.
- `_dynamic_attrs`: Dynamic attributes of the navigator.
- `_full_display_name`: Full display name of the navigator.
- `_full_name`: Full name of the navigator.
- `_name`: Name of the navigator.
- `_parent`: Parent of the navigator.
```
--------------------------------
### POST /configure
Source: https://api4jenkins.readthedocs.io/en/latest/user/api.html
Configures a view using XML data.
```APIDOC
## POST /configure
### Description
Updates the configuration of the view using the provided XML.
### Method
POST
### Parameters
#### Request Body
- **xml** (string) - Optional - The XML configuration string.
```
--------------------------------
### Plugin Management
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Operations for managing Jenkins plugins including installation, status checks, and uninstallation.
```APIDOC
## Plugin Management
### Description
Manage Jenkins plugins by checking installation status, installing new plugins, and uninstalling existing ones.
### Methods
- `j.plugins`: Access the plugin manager.
- `plugin.uninstall()`: Uninstall a specific plugin.
- `jenkins.plugins.install(*names, block=True)`: Install plugins by name.
- `jenkins.plugins.check_updates_server()`: Refresh the update center.
### Properties
- `installation_done` (bool): Returns True if plugin installation is complete.
- `restart_required` (bool): Returns True if a Jenkins restart is required after plugin changes.
```
--------------------------------
### Get Jenkins Object from Item
Source: https://api4jenkins.readthedocs.io/en/latest/_sources/user/example.rst.txt
Obtain the Jenkins object associated with a specific job item.
```python
>>> j = item.jenkins
```
--------------------------------
### Define AsyncGetMixIn class
Source: https://api4jenkins.readthedocs.io/en/latest/_modules/api4jenkins/report.html
Provides an asynchronous get method to retrieve items by name from an iterable.
```python
class AsyncGetMixIn:
async def get(self, name):
async for item in self:
if item.name == name:
return item
```
--------------------------------
### Jenkins API - N Section
Source: https://api4jenkins.readthedocs.io/en/latest/genindex.html
Details on entities and classes starting with 'N' in the Jenkins API.
```APIDOC
## N
### Classes and Properties
- **name** (api4jenkins.credential.AsyncCredential property)
- **AsyncDomain** (api4jenkins.credential.AsyncDomain property)
- **Credential** (api4jenkins.credential.Credential property)
- **Domain** (api4jenkins.credential.Domain property)
- **AsyncBitbucketSCMNavigator** (api4jenkins.job.AsyncBitbucketSCMNavigator property)
- **AsyncExternalJob** (api4jenkins.job.AsyncExternalJob property)
- **AsyncFolder** (api4jenkins.job.AsyncFolder property)
- **AsyncFreeStyleProject** (api4jenkins.job.AsyncFreeStyleProject property)
- **AsyncGitHubSCMNavigator** (api4jenkins.job.AsyncGitHubSCMNavigator property)
- **AsyncIvyModuleSet** (api4jenkins.job.AsyncIvyModuleSet property)
- **AsyncJob** (api4jenkins.job.AsyncJob property)
- **AsyncMatrixProject** (api4jenkins.job.AsyncMatrixProject property)
- **AsyncMavenModuleSet** (api4jenkins.job.AsyncMavenModuleSet property)
- **AsyncMultiJobProject** (api4jenkins.job.AsyncMultiJobProject property)
- **AsyncOrganizationFolder** (api4jenkins.job.AsyncOrganizationFolder property)
- **AsyncPipelineMultiBranchDefaultsProject** (api4jenkins.job.AsyncPipelineMultiBranchDefaultsProject property)
- **AsyncProject** (api4jenkins.job.AsyncProject property)
- **AsyncWorkflowJob** (api4jenkins.job.AsyncWorkflowJob property)
- **AsyncWorkflowMultiBranchProject** (api4jenkins.job.AsyncWorkflowMultiBranchProject property)
- **BitbucketSCMNavigator** (api4jenkins.job.BitbucketSCMNavigator property)
- **ExternalJob** (api4jenkins.job.ExternalJob property)
- **Folder** (api4jenkins.job.Folder property)
- **FreeStyleProject** (api4jenkins.job.FreeStyleProject property)
- **GitHubSCMNavigator** (api4jenkins.job.GitHubSCMNavigator property)
- **IvyModuleSet** (api4jenkins.job.IvyModuleSet property)
- **Job** (api4jenkins.job.Job property)
- **MatrixProject** (api4jenkins.job.MatrixProject property)
- **MavenModuleSet** (api4jenkins.job.MavenModuleSet property)
- **MultiJobProject** (api4jenkins.job.MultiJobProject property)
- **OrganizationFolder** (api4jenkins.job.OrganizationFolder property)
- **PipelineMultiBranchDefaultsProject** (api4jenkins.job.PipelineMultiBranchDefaultsProject property)
- **Project** (api4jenkins.job.Project property)
- **WorkflowJob** (api4jenkins.job.WorkflowJob property)
- **WorkflowMultiBranchProject** (api4jenkins.job.WorkflowMultiBranchProject property)
- **AsyncConfigurationMixIn** (api4jenkins.mix.AsyncConfigurationMixIn property)
- **ConfigurationMixIn** (api4jenkins.mix.ConfigurationMixIn property)
- **Parameter** (api4jenkins.mix.Parameter attribute)
- **AsyncDockerComputer** (api4jenkins.node.AsyncDockerComputer property)
- **AsyncEC2Computer** (api4jenkins.node.AsyncEC2Computer property)
- **AsyncKubernetesComputer** (api4jenkins.node.AsyncKubernetesComputer property)
- **AsyncMasterComputer** (api4jenkins.node.AsyncMasterComputer property)
- **AsyncNode** (api4jenkins.node.AsyncNode property)
- **AsyncSlaveComputer** (api4jenkins.node.AsyncSlaveComputer property)
- **DockerComputer** (api4jenkins.node.DockerComputer property)
- **EC2Computer** (api4jenkins.node.EC2Computer property)
- **KubernetesComputer** (api4jenkins.node.KubernetesComputer property)
- **MasterComputer** (api4jenkins.node.MasterComputer property)
- **Node** (api4jenkins.node.Node property)
- **SlaveComputer** (api4jenkins.node.SlaveComputer property)
- **ApiToken** (api4jenkins.user.ApiToken attribute)
- **AllView** (api4jenkins.view.AllView property)
- **AsyncAllView** (api4jenkins.view.AsyncAllView property)
- **AsyncDashboard** (api4jenkins.view.AsyncDashboard property)
- **AsyncListView** (api4jenkins.view.AsyncListView property)
- **AsyncMyView** (api4jenkins.view.AsyncMyView property)
- **AsyncNestedView** (api4jenkins.view.AsyncNestedView property)
- **AsyncSectionedView** (api4jenkins.view.AsyncSectionedView property)
- **AsyncView** (api4jenkins.view.AsyncView property)
- **Dashboard** (api4jenkins.view.Dashboard property)
- **ListView** (api4jenkins.view.ListView property)
- **MyView** (api4jenkins.view.MyView property)
- **NestedView** (api4jenkins.view.NestedView property)
- **SectionedView** (api4jenkins.view.SectionedView property)
- **View** (api4jenkins.view.View property)
### Functions
- **NameMixIn** (class in api4jenkins.job)
- **NestedView** (class in api4jenkins.view)
- **new_async_http_client()** (in module api4jenkins.http)
- **new_http_client()** (in module api4jenkins.http)
- **new_item()** (in module api4jenkins.item)
- **Node** (class in api4jenkins.node)
- **nodes** (api4jenkins.AsyncJenkins property)
- (api4jenkins.Jenkins property)
- **Nodes** (class in api4jenkins.node)
```
--------------------------------
### AsyncFolder class methods
Source: https://api4jenkins.readthedocs.io/en/latest/_modules/api4jenkins/job.html
Methods for managing Jenkins folders, including creating items, listing jobs, and copying.
```python
class AsyncFolder(AsyncJob):
async def create(self, name, xml):
return await self.handle_req('POST', 'createItem', params={'name': name},
headers=self.headers, content=xml)
async def get(self, name):
resp = await self.api_json(tree='jobs[name,url]')
for item in resp['jobs']:
if name == item['name']:
return self._new_item(__name__, item)
return None
async def aiter(self, depth=0):
for item in (await self.api_json(tree=_make_query(depth)))['jobs']:
for job in _iter_jobs(self.jenkins, item):
yield job
async def copy(self, src, dest):
params = {'name': dest, 'mode': 'copy', 'from': src}
return await self.handle_req('POST', 'createItem', params=params)
async def reload(self):
return await self.handle_req('POST', 'reload')
@property
def views(self):
return Views(self)
@property
def credentials(self):
return AsyncCredentials(self.jenkins,
f'{self.url}credentials/store/folder/')
async def __call__(self, depth):
async for job in self.aiter(depth):
yield job
```