I am trying to create a TeamCity build configuration for creating a Docker Image.
For redundancy, I want the first Build Step to check whether Docker is running on the TeamCity server, and start it if necessary.
I have created the following PowerShell script that does exactly that. The script even waits until Docker is fully functional before finishing.
# This File checks if docker is running, and starts it if necessary, waiting until it has finished starting up before exiting
# ---------
# VARIABLES
# ---------
$TimeoutInterval = 10 #Timeout interval for checking whether docker has finished starting, in seconds
$DockerPath = "C:\Program Files\Docker\Docker\Docker for Windows.exe"
# ---------
# FUNCTIONS
# ---------
Function ProcessRunning([string] $ProcessName) {
[bool] $Return = $False
if ( Get-Process | Where-Object {$_.Name -like $ProcessName} ) {
$Return = $True
}
Return $Return
}
# -------
# PROGRAM
# -------
# Enables Error Action Preference to stop to enable try-catches
$ErrorActionPreference = 'Stop'
if(ProcessRunning("Docker for Windows")){
echo "Docker is running"
echo ""
docker version
}else{
echo "Docker is not running"
echo ""
echo "Starting Docker"
echo ""
Start-Process $DockerPath
#Waits while Docker has not finished starting up
$dockerStarting = $true
while($dockerStarting){
try{
docker version
$dockerStarting = $false
}catch{
echo ""
echo "Docker is still starting up..."
echo ""
$dockerStarting = $true
Wait-Event -Timeout $TimeoutInterval
}
}
echo ""
echo "Docker has finished starting up!"
echo ""
}
This script works fine when executed locally on the TeamCity server. However, when I attempt to run it as a BuildStep, it appears to ignore the try-catch block like it did in my local version before I set the $ErrorActionPreference = 'Stop'
Specifically, the docker version
command fails as I intended it to to indicate that Docker is not yet fully running. However, the try-catch block fails to catch it as it does when run locally on the server.
I have already tried both values of Format stderr output as:
as well as Script execution mode:
, but the result remains the same: The script throws an error, and Docker is not started on the TeamCity Server.
Now, my basic question is: Is what I'm trying even technically possible? Because I could imagine that TeamCity employs some sort of safeguard mechanism that prevents certain changes on the Server it's run from. Then again, I have in the past successfully employed PowerShell scripts to copy and delete files on the Server, so honestly, at this point I'm more confused than anything about why this doesn't seem to work.
Any input on this would be greatly appreciated.