Delete Jenkins Empty folder and Pipelines

I need a help to delete Jenkins Pipeline job and empty folder using python script pipeline

Hello and welcome to this community, @Ryan1. :wave:

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.

  1. Install Required Libraries: Ensure you have the requests library installed.
  2. Authenticate with Jenkins: Use your Jenkins credentials to authenticate.
  3. Delete the Job: Use the Jenkins REST API to delete the job.
  4. 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)
  1. Ensure you have the requests library installed using pip install requests.
  2. Use HTTPBasicAuth for authentication.
  3. The delete_jenkins_job function sends a POST request to the Jenkins REST API to delete the specified job.
  4. The delete_empty_folder function uses os.rmdir to delete the specified folder, ensuring it is empty.