zorro1224
zorro1224

Reputation: 73

Running PSSession from jenkinsfile

Within my Jenkinsfile, I am trying to open a powershell PSSession to a remote machine to install some software, but it seems to ignore this step and just run all the next commands locally, instead of the machine I am trying to PSSession to..

Here is my code:

pipeline {
agent { label 'slave-windows' }
stages {
    stage('Parameters') {
        steps {
            script {
            properties([
                parameters([
                            string(name: 'VM_NAME', defaultValue: '', description: 'Enter the VM name'),
                ])
            ])
            }
        }
    }
    stage('install') {
        steps {
            powershell """
                Enter-PSSession ${params.VM_NAME}
                New-Item "C:\\salt" -itemType Directory
                [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
                Invoke-WebRequest -Uri "https://repo.saltproject.io/windows/Salt-Minion-3004.2-Py3-AMD64-Setup.exe" -OutFile “C:\\salt\\Salt-Minion-3004.2-Py3-AMD64-Setup.exe"
                C:\\salt\\Salt-Minion-3004.2-Py3-AMD64-Setup.exe /S /master=master /minion-name=${params.VM_NAME}
            """
        }
    }
}

I don't see any output in the build log regarding the PSSession command, but it goes ahead and runs all the remaining steps locally on the windows slave instead. Any ideas?

Upvotes: 0

Views: 491

Answers (1)

zett42
zett42

Reputation: 27756

Enter-PSSession is for interactive use only. For scripting, use Invoke-Command:

powershell '''
    Invoke-Command -ComputerName $env:VM_NAME -ScriptBlock {
        # code to run on the remote machine
    }
'''
  • Note that using Groovy string interpolation is very insecure, because it is vulnerable to script injection and secret things like credentials may be logged. Shell scripts should always be single-quoted or triple-single quoted so this is not possible. Pass pipeline parameters as environment variables, which is easy because they become environment vars automatically. In the sample above, it is PowerShell that resolves $env:VM_NAME, not Groovy. To pass script variables, use withEnv.
  • If necessary use -Credential parameter to use different credentials.
  • In your case it shouldn't be necessary, but for more complex scenarios you can use New-PSSession to explicitly create a session and pass it for -Session argument of Invoke-Command. This would allow you to switch back and forth between remote and local session.

Upvotes: 1

Related Questions