Search code examples
windowsjenkinsgroovyjenkins-agent

How to execute CMD command on jenkins windows agent using groovy?


I am trying to execute cmd /c echo hello using groovy on a jenkins agent running on windows.

Here is my groovy:

node('WINDOWS-AGENT-1') {
    def cmd_command = "cmd /c echo hello"
    cmd_command.execute()
}

And I can see in the job logs that it is indeed running on that windows agent: 'Running on WINDOWS-AGENT-1'

But I get an error: java.io.IOException: error=2, No such file or directory

And if I try to run linux like ls -l it works fine. Shows me the files of my Jenkins controller.

How can I execute this CMD command on my Windows Jenkins agent from my groovy script?


Solution

  • If your intention is to execute a command on a given node, you need to use one of the Jenkins Pipeline's steps designed to execute shell scripts (e.g. sh or bat). You need to be aware that any Groovy code in your Jenkinsfile is always executed on the master node:

    "1. Except for the steps themselves, all of the Pipeline logic, the Groovy conditionals, loops, etc execute on the master. Whether simple or complex! Even inside a node block!"


    Source: https://jenkins.io/blog/2017/02/01/pipeline-scalability-best-practice/#fundamentals

    node('WINDOWS-SLAVE-1') {
        bat "cmd /c echo hello"
    }