Search code examples
jenkins-groovyjenkins-cli

Reboot Windows Computers in Groovy on Jenkins


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.


Solution

  • 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