Advertisement
ceztko

Get the actual running computer at any context

Apr 22nd, 2024 (edited)
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import org.jenkinsci.plugins.workflow.cps.CpsThread;
  2.  
  3. echo "Computer name: ${getCurrentComputerSafe().displayName}" // Prints: Built-In Node
  4.  
  5. pipeline {
  6.     agent any
  7.  
  8.     stages {
  9.         stage('Stage1') {
  10.             agent {
  11.                 label 'MyNode'
  12.             }
  13.             steps {
  14.                 script {
  15.                     echo "Computer name: ${getCurrentComputerSafe().displayName}" // Prints: MyNode
  16.                 }
  17.             }
  18.         }
  19.     }
  20. }
  21.  
  22. @NonCPS
  23. static private Computer getCurrentComputerSafe()
  24. {
  25.     // Try get executing computer first
  26.     def current = Computer.currentComputer();
  27.     if (current != null)
  28.         return current;
  29.  
  30.     // Reverse iterate steps to find a delegate computer that
  31.     // will execute.
  32.     def threads = CpsThread.current().group.threads.toArray();
  33.     for (int i = threads.length - 1; i >= 0; i--)
  34.     {
  35.         def thread = threads[i];
  36.         if (thread.step == null)
  37.             continue;
  38.  
  39.         def filePath = thread.step.context.get(hudson.FilePath);
  40.         if (filePath == null)
  41.             continue;
  42.  
  43.         return filePath.toComputer();
  44.     }
  45.  
  46.     // As a last measure, return the master computer
  47.     def computers = Jenkins.instance.computers;
  48.     for (int i = 0; i < threads.length; i++)
  49.     {
  50.         def computer = computers[i];
  51.         if (computer instanceof Jenkins.MasterComputer)
  52.             return computer;
  53.     }
  54.  
  55.     throw new Exception('Unexpected no master computer found');
  56. }
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement