0

I want to write a restart command in Groovy to reboot Windows machines on Jenkins.

I know that the shutdown command is shutdown /r /f but how would I use this in Groovy? Again, these servers will be accessed remotely.

treatyoself
  • 83
  • 2
  • 16

1 Answers1

1

I am not sure if it helps, but you should be able to use the Jenkins DSL 'bat' command to execute that command on a windows agent.

def agentNameOrLabelGroup = 'windows'

node (agentNameOrLabelGroup) {
  bat 'shutdown /r /f'
}

I would suggest providing a delay so that the executing context from Jenkins has time to release the agent. Otherwise I'd expect that shutting down the agent while the agent is running will cause the job to fail.

If you need multiple machines, I think I would use the jenkins plugin for nodesByLabel to get all 'windows' machines, then just loop through them.

def agents = nodesByLabel(label: 'windows')

for (agent in agents) {
  node (agent) {
    bat 'shutdown /r /f'
  }
}

https://jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#nodesbylabel-list-of-nodes-by-label-by-default-excludes-offline-nodes

Best of Luck

Jeremiah
  • 1,145
  • 6
  • 8
  • 1
    I have not done this myself, but if I had to guess at it I would: Spawn a subshell to execute the shutdown & add a delay at the start of the subshell to allow the primary shell to terminate and the job to complete. https://stackoverflow.com/questions/4215405/how-to-run-a-cmd-exe-batch-file-in-a-sub-shell https://stackoverflow.com/questions/166044/sleeping-in-a-batch-file – Jeremiah Oct 04 '19 at 23:16
  • I misread your question, I believe I tried to answer more how to allow the shutdown to execute without killing the job. Apologies for my confusion. -- To answer your actual question of telling when the restart is completed.... I would configure the windows machine to start the Jenkins agent on startup. At that point you can target the agent explicitly `node(agent) { echo "${agent} online"}`. That should block while the agent is offline, and print when it's reconnected. – Jeremiah Oct 05 '19 at 09:05
  • Instead of taking the node offline, I am not accepting any tasks. Because if I put the node offline then the script will not execute. Is there a way to tell if the reboot has finished if I am only making it so that the node is not accepting any tasks? – treatyoself Oct 06 '19 at 16:17