I need a help to delete Jenkins Pipeline job and empty folder using python script pipeline
Hello and welcome to this community, @Ryan1.
To delete a Jenkins Pipeline job and its corresponding folder using a Python script, you can use the Jenkins REST API.
Below is a step-by-step guide and an untested Python script to achieve this.
- Install Required Libraries: Ensure you have the
requests
library installed. - Authenticate with Jenkins: Use your Jenkins credentials to authenticate.
- Delete the Job: Use the Jenkins REST API to delete the job.
- Delete the Folder: Ensure the folder is empty before deleting it.
import requests
from requests.auth import HTTPBasicAuth
# Jenkins server details
jenkins_url = 'http://your-jenkins-server'
job_name = 'your-job-name'
username = 'your-username'
api_token = 'your-api-token'
# Function to delete a Jenkins job
def delete_jenkins_job(jenkins_url, job_name, username, api_token):
delete_job_url = f"{jenkins_url}/job/{job_name}/doDelete"
response = requests.post(delete_job_url, auth=HTTPBasicAuth(username, api_token))
if response.status_code == 200:
print(f"Successfully deleted job: {job_name}")
else:
print(f"Failed to delete job: {job_name}, Status Code: {response.status_code}, Response: {response.text}")
# Function to delete an empty folder
def delete_empty_folder(folder_path):
import os
try:
os.rmdir(folder_path)
print(f"Successfully deleted folder: {folder_path}")
except OSError as e:
print(f"Error: {folder_path} : {e.strerror}")
# Delete the Jenkins job
delete_jenkins_job(jenkins_url, job_name, username, api_token)
# Delete the corresponding folder (ensure the folder is empty)
folder_path = '/path/to/your/folder'
delete_empty_folder(folder_path)
- Ensure you have the
requests
library installed usingpip install requests
. - Use
HTTPBasicAuth
for authentication. - The
delete_jenkins_job
function sends a POST request to the Jenkins REST API to delete the specified job. - The
delete_empty_folder
function usesos.rmdir
to delete the specified folder, ensuring it is empty.