Sign in
agent:

Get the last 50 lines of the console log for the Jenkins job above.

There was a problem that the LLM was not able to address. Please rephrase your prompt and try again.

This code fetches the last 50 lines of the console log for the last build of the specified Jenkins job using the Jenkins API.

import json import requests from requests.auth import HTTPBasicAuth # Get environment variables JENKINS_USERNAME = getEnvVar('JENKINS_USERNAME') JENKINS_API_TOKEN = getEnvVar('JENKINS_API_TOKEN') JENKINS_URL = getEnvVar('JENKINS_URL') # Print input parameters print(f"Input Parameters:\njob_name: {job_name}") # Jenkins API URL to get the last build number url_last_build = f"{JENKINS_URL}/job/{job_name}/lastBuild/api/json" # Headers for authentication headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' } # Make the request to Jenkins API to get the last build number response_last_build = requests.get(url_last_build, headers=headers, auth=HTTPBasicAuth(JENKINS_USERNAME, JENKINS_API_TOKEN)) if response_last_build.status_code == 200: last_build_info = response_last_build.json() last_build_number = last_build_info['number'] # Jenkins API URL to get the console log url_console_log = f"{JENKINS_URL}/job/{job_name}/{last_build_number}/logText/progressiveText?start=0" # Make the request to Jenkins API to get the console log response_console_log = requests.get(url_console_log, headers=headers, auth=HTTPBasicAuth(JENKINS_USERNAME, JENKINS_API_TOKEN)) if response_console_log.status_code == 200: console_log = response_console_log.text last_50_lines = '\n'.join(console_log.split('\n')[-50:]) print(f"Output:\n{last_50_lines}") else: print(f"Failed to fetch console log. Status code: {response_console_log.status_code}") else: print(f"Failed to fetch last build number. Status code: {response_last_build.status_code}")
copied