How to stop VPN connection started from Jenkins? I've just discovered this site and I would like to ask my first question.

I have a pipeline project on Jenkins that basically do this:


SVN update
Build
Deploy


As the deploy target machine is on a different network, I need to start an OpenVPN connection. This works fine using bat 'start openvpn config.ovpn'.

The problem is that I need to drop the VPN connection once the process has finished and there is no stop command for OpenVPN.

My first approach was to save the process ID that started OpenVPN and kill it later. Something like this:

stage('Connect VPN') {
        bat '''wmic process get parentprocessid,name | grep WMIC | tr -d \'WMIC.exe \' &gt; wmic_pid
            start openvpn myconfig.ovpn'''
    }

stage('Deploy') {
    // Deployment process
}

stage('Disconnect VPN') {
    env.WMID_PID=readFile('wmic_pid').trim()
    bat 'taskkill -pid %WMID_PID% -t'
}


However, for some reason the process ID saved using wmic does not match with the one used by OpenVPN. This procedure works fine when its executed manually on a cmd.

Any ideas?

PS: I'm on a Windows Server 2012.
Your question is sitting unanswered here because you're way "out in the weeds" - running pretty idiosyncratic batch scripts that seem to leverage cygwin on Windows, in short, you're in the "wtf" category here.  That's ok!  In this work, all of us are in this place for a lot of our day.

I suggest you consider switching these up for powershell tasks, you can use: 

node {
    powershell 'get-process "Openvpn" | stop-process -force'
}


to help with this.  This will simplify your build server and remove external dependencies on cygwin- which if you've ever grappled with at any scale, is a real monster.  It's tough to install automatically, tough to keep up to date, a vuln factory, and poorly maintained.

Perhaps even bigger picture though, using a VPN tunnel in a deployment process is slightly unorthodox.  You might consider pushing an artifact to a repository that both Jenkins and your target server have access to, then polling from the target server for the presence of a new build, then installing it.  Or simply decouple your build and deploy phases with a manual step- one where you log into your production environment to kick off a deployment after a build/test succeeds.