如何用Jenkins参数化Pipeline脚本检查节点状态及报错排查
Fixing Jenkins Pipeline Node Status Check Error
Let's walk through the issues in your current script and fix them to properly check a node's online/offline status.
Why You're Getting That Error
Looking at the error message and your code, there are three critical issues:
- Parameter Name Mismatch: You defined the parameter as
JUMP_HOSTbut tried to access it asparams.JUMPHOST(missing the underscore). This can lead to passing an empty or null value togetSlave(). - Undefined Variable: You commented out the loop that defines the
slavevariable, but still tried to useslave.namelater in your code. Groovy has no idea whatslaverefers to here, which contributes to the method mismatch error. - Missing Null Check: If the specified node doesn't exist, calling
getComputer()on a null slave will throw another error—we need to handle that case gracefully.
Corrected Pipeline Script
Here's the fixed version with explanations of key changes:
import hudson.model.* pipeline { agent none parameters { string(defaultValue: "", description: 'Enter the name of the node/slave to check', name: 'JUMP_HOST') } stages { stage("Check Node Status"){ steps{ script{ def statusMessage = [] // Get the slave node using the correct parameter name def targetSlave = hudson.model.Hudson.instance.getSlave(params.JUMP_HOST) // First check if the node exists if (!targetSlave) { statusMessage += "Error: Node '${params.JUMP_HOST}' does not exist in Jenkins!" } else { // Check if the node's computer is online def isOnline = targetSlave.getComputer().isOnline() if (isOnline) { statusMessage += "Node '${targetSlave.name}' is **online**" } else { statusMessage += "Node '${targetSlave.name}' is **offline**" } } // Print the status message statusMessage.each { println it } } } } } }
Key Improvements Made:
- Fixed Parameter Access: Used
params.JUMP_HOSTto match the parameter definition. - Added Node Existence Check: Prevented null pointer exceptions by verifying the node exists before checking its status.
- Defined
targetSlaveVariable: Replaced the undefinedslavevariable with a properly declared one that references the target node. - Clearer Status Messages: Used formatted strings to make output more readable, with bold text for online/offline status.
- Better Error Handling: Added a message for when the specified node doesn't exist, so you get useful feedback instead of a cryptic error.
How to Test It
- Save this script as a Jenkins Pipeline job.
- Run the job, enter the exact name of a node/slave in the
JUMP_HOSTparameter field. - Check the console output to see the node's status (or an error if the node doesn't exist).
内容的提问来源于stack exchange,提问作者Suganthan Raj
相关产品推荐
相关产品推荐

