TeamCity ~ Start Docker on Server via Build Step











up vote
1
down vote

favorite












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 FilesDockerDockerDocker 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.










share|improve this question


























    up vote
    1
    down vote

    favorite












    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 FilesDockerDockerDocker 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.










    share|improve this question
























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      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 FilesDockerDockerDocker 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.










      share|improve this question













      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 FilesDockerDockerDocker 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.







      powershell docker teamcity






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 19 at 9:38









      Kira Resari

      478




      478
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote













          Okay, so I tried around a lot, and eventually found a solution that allows me to check if Docker is running via a TeamCity build step and successfully start it if not.



          This actually turned out to be a two-tier problem, with two separate things having to be done in order to make it work:



          1.) Run the TeamCity Build Agent Service as an elevated local account



          In my case, I had the TeamCity Build Agent Service running under the SYSTEM account. I switched it to an Administrator account using:



          Services
          ↳TeamCity Build Agent
          ↳Log On>Log on as
          ↳◉This account: .Administrator


          2.) Use a "clean" skript that does not rely on try-catch to see if Docker is running



          The final PowerShell Skript that I'm using now and that works nicely looks like this:



          # 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 FilesDockerDockerDocker for Windows.exe"


          # ---------
          # FUNCTIONS
          # ---------

          Function ProcessRunning([string] $ProcessName) {
          [bool] $Return = $False
          if ( Get-Process | Where-Object {$_.Name -like $ProcessName} ) {
          $Return = $True
          }
          Return $Return
          }

          # Determines if a Service exists with a name as defined in $ServiceName.
          Function ServiceExists([string] $ServiceName) {
          [bool] $Return = $False
          if ( Get-Service "$ServiceName*" -Include $ServiceName ) {
          $Return = $True
          }
          Return $Return
          }

          # Determines if a Service with a name as defined in $ServiceName exists and is running
          Function ServiceRunning([string] $ServiceName) {
          [bool] $Return = $False
          Write-Host "Checking if Service "$ServiceName" exists and is running"
          Write-Host ""
          if ( Get-Service "$ServiceName*" -Include $ServiceName ) {

          $arrService = Get-Service -Include $ServiceName

          if ( $arrService.Status -eq "Running" ) {
          Write-Host "Service "$ServiceName" exists, and is running!"
          Write-Host ""
          $Return = $True
          }else{
          Write-Host "Service "$ServiceName" exists, but is not running!"
          Write-Host ""
          }
          }else{
          Write-Host "Service "$ServiceName" does not exist!"
          Write-Host ""
          }
          Return $Return
          }


          # -------
          # PROGRAM
          # -------

          if(ProcessRunning("Docker for Windows")){
          Write-Host "Docker is running"
          Write-Host ""
          docker version
          }else{
          Write-Host "Docker is not running"
          Write-Host ""
          Write-Host "Starting Docker"
          Write-Host ""
          Start-Process $DockerPath

          #Waits while Docker has not finished starting up
          $dockerStarting = $true
          while($dockerStarting){
          if((ServiceRunning("com.docker.service")) -and (ServiceRunning("docker"))){
          Write-Host ""
          Write-Host "Docker has finished starting up!"
          Write-Host ""
          docker version
          $dockerStarting = $false
          }else{
          Write-Host ""
          Write-Host "Docker is still starting up..."
          Write-Host ""

          #Attempts to start the relevant services
          if(!(ServiceRunning("com.docker.service"))){
          if(ServiceExists("com.docker.service")){
          Start-Service "com.docker.service"
          }
          }
          if(!(ServiceRunning("docker"))){
          if(ServiceExists("docker")){
          Start-Service "docker"
          }
          }

          $dockerStarting = $true
          Wait-Event -Timeout $TimeoutInterval
          }
          }
          }


          I still have no idea why try-catch isn't working in TeamCity, so if someone knows the answer to that, please comment.



          Anyway, I hope this solution is helpful to someone.






          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53371823%2fteamcity-start-docker-on-server-via-build-step%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            0
            down vote













            Okay, so I tried around a lot, and eventually found a solution that allows me to check if Docker is running via a TeamCity build step and successfully start it if not.



            This actually turned out to be a two-tier problem, with two separate things having to be done in order to make it work:



            1.) Run the TeamCity Build Agent Service as an elevated local account



            In my case, I had the TeamCity Build Agent Service running under the SYSTEM account. I switched it to an Administrator account using:



            Services
            ↳TeamCity Build Agent
            ↳Log On>Log on as
            ↳◉This account: .Administrator


            2.) Use a "clean" skript that does not rely on try-catch to see if Docker is running



            The final PowerShell Skript that I'm using now and that works nicely looks like this:



            # 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 FilesDockerDockerDocker for Windows.exe"


            # ---------
            # FUNCTIONS
            # ---------

            Function ProcessRunning([string] $ProcessName) {
            [bool] $Return = $False
            if ( Get-Process | Where-Object {$_.Name -like $ProcessName} ) {
            $Return = $True
            }
            Return $Return
            }

            # Determines if a Service exists with a name as defined in $ServiceName.
            Function ServiceExists([string] $ServiceName) {
            [bool] $Return = $False
            if ( Get-Service "$ServiceName*" -Include $ServiceName ) {
            $Return = $True
            }
            Return $Return
            }

            # Determines if a Service with a name as defined in $ServiceName exists and is running
            Function ServiceRunning([string] $ServiceName) {
            [bool] $Return = $False
            Write-Host "Checking if Service "$ServiceName" exists and is running"
            Write-Host ""
            if ( Get-Service "$ServiceName*" -Include $ServiceName ) {

            $arrService = Get-Service -Include $ServiceName

            if ( $arrService.Status -eq "Running" ) {
            Write-Host "Service "$ServiceName" exists, and is running!"
            Write-Host ""
            $Return = $True
            }else{
            Write-Host "Service "$ServiceName" exists, but is not running!"
            Write-Host ""
            }
            }else{
            Write-Host "Service "$ServiceName" does not exist!"
            Write-Host ""
            }
            Return $Return
            }


            # -------
            # PROGRAM
            # -------

            if(ProcessRunning("Docker for Windows")){
            Write-Host "Docker is running"
            Write-Host ""
            docker version
            }else{
            Write-Host "Docker is not running"
            Write-Host ""
            Write-Host "Starting Docker"
            Write-Host ""
            Start-Process $DockerPath

            #Waits while Docker has not finished starting up
            $dockerStarting = $true
            while($dockerStarting){
            if((ServiceRunning("com.docker.service")) -and (ServiceRunning("docker"))){
            Write-Host ""
            Write-Host "Docker has finished starting up!"
            Write-Host ""
            docker version
            $dockerStarting = $false
            }else{
            Write-Host ""
            Write-Host "Docker is still starting up..."
            Write-Host ""

            #Attempts to start the relevant services
            if(!(ServiceRunning("com.docker.service"))){
            if(ServiceExists("com.docker.service")){
            Start-Service "com.docker.service"
            }
            }
            if(!(ServiceRunning("docker"))){
            if(ServiceExists("docker")){
            Start-Service "docker"
            }
            }

            $dockerStarting = $true
            Wait-Event -Timeout $TimeoutInterval
            }
            }
            }


            I still have no idea why try-catch isn't working in TeamCity, so if someone knows the answer to that, please comment.



            Anyway, I hope this solution is helpful to someone.






            share|improve this answer

























              up vote
              0
              down vote













              Okay, so I tried around a lot, and eventually found a solution that allows me to check if Docker is running via a TeamCity build step and successfully start it if not.



              This actually turned out to be a two-tier problem, with two separate things having to be done in order to make it work:



              1.) Run the TeamCity Build Agent Service as an elevated local account



              In my case, I had the TeamCity Build Agent Service running under the SYSTEM account. I switched it to an Administrator account using:



              Services
              ↳TeamCity Build Agent
              ↳Log On>Log on as
              ↳◉This account: .Administrator


              2.) Use a "clean" skript that does not rely on try-catch to see if Docker is running



              The final PowerShell Skript that I'm using now and that works nicely looks like this:



              # 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 FilesDockerDockerDocker for Windows.exe"


              # ---------
              # FUNCTIONS
              # ---------

              Function ProcessRunning([string] $ProcessName) {
              [bool] $Return = $False
              if ( Get-Process | Where-Object {$_.Name -like $ProcessName} ) {
              $Return = $True
              }
              Return $Return
              }

              # Determines if a Service exists with a name as defined in $ServiceName.
              Function ServiceExists([string] $ServiceName) {
              [bool] $Return = $False
              if ( Get-Service "$ServiceName*" -Include $ServiceName ) {
              $Return = $True
              }
              Return $Return
              }

              # Determines if a Service with a name as defined in $ServiceName exists and is running
              Function ServiceRunning([string] $ServiceName) {
              [bool] $Return = $False
              Write-Host "Checking if Service "$ServiceName" exists and is running"
              Write-Host ""
              if ( Get-Service "$ServiceName*" -Include $ServiceName ) {

              $arrService = Get-Service -Include $ServiceName

              if ( $arrService.Status -eq "Running" ) {
              Write-Host "Service "$ServiceName" exists, and is running!"
              Write-Host ""
              $Return = $True
              }else{
              Write-Host "Service "$ServiceName" exists, but is not running!"
              Write-Host ""
              }
              }else{
              Write-Host "Service "$ServiceName" does not exist!"
              Write-Host ""
              }
              Return $Return
              }


              # -------
              # PROGRAM
              # -------

              if(ProcessRunning("Docker for Windows")){
              Write-Host "Docker is running"
              Write-Host ""
              docker version
              }else{
              Write-Host "Docker is not running"
              Write-Host ""
              Write-Host "Starting Docker"
              Write-Host ""
              Start-Process $DockerPath

              #Waits while Docker has not finished starting up
              $dockerStarting = $true
              while($dockerStarting){
              if((ServiceRunning("com.docker.service")) -and (ServiceRunning("docker"))){
              Write-Host ""
              Write-Host "Docker has finished starting up!"
              Write-Host ""
              docker version
              $dockerStarting = $false
              }else{
              Write-Host ""
              Write-Host "Docker is still starting up..."
              Write-Host ""

              #Attempts to start the relevant services
              if(!(ServiceRunning("com.docker.service"))){
              if(ServiceExists("com.docker.service")){
              Start-Service "com.docker.service"
              }
              }
              if(!(ServiceRunning("docker"))){
              if(ServiceExists("docker")){
              Start-Service "docker"
              }
              }

              $dockerStarting = $true
              Wait-Event -Timeout $TimeoutInterval
              }
              }
              }


              I still have no idea why try-catch isn't working in TeamCity, so if someone knows the answer to that, please comment.



              Anyway, I hope this solution is helpful to someone.






              share|improve this answer























                up vote
                0
                down vote










                up vote
                0
                down vote









                Okay, so I tried around a lot, and eventually found a solution that allows me to check if Docker is running via a TeamCity build step and successfully start it if not.



                This actually turned out to be a two-tier problem, with two separate things having to be done in order to make it work:



                1.) Run the TeamCity Build Agent Service as an elevated local account



                In my case, I had the TeamCity Build Agent Service running under the SYSTEM account. I switched it to an Administrator account using:



                Services
                ↳TeamCity Build Agent
                ↳Log On>Log on as
                ↳◉This account: .Administrator


                2.) Use a "clean" skript that does not rely on try-catch to see if Docker is running



                The final PowerShell Skript that I'm using now and that works nicely looks like this:



                # 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 FilesDockerDockerDocker for Windows.exe"


                # ---------
                # FUNCTIONS
                # ---------

                Function ProcessRunning([string] $ProcessName) {
                [bool] $Return = $False
                if ( Get-Process | Where-Object {$_.Name -like $ProcessName} ) {
                $Return = $True
                }
                Return $Return
                }

                # Determines if a Service exists with a name as defined in $ServiceName.
                Function ServiceExists([string] $ServiceName) {
                [bool] $Return = $False
                if ( Get-Service "$ServiceName*" -Include $ServiceName ) {
                $Return = $True
                }
                Return $Return
                }

                # Determines if a Service with a name as defined in $ServiceName exists and is running
                Function ServiceRunning([string] $ServiceName) {
                [bool] $Return = $False
                Write-Host "Checking if Service "$ServiceName" exists and is running"
                Write-Host ""
                if ( Get-Service "$ServiceName*" -Include $ServiceName ) {

                $arrService = Get-Service -Include $ServiceName

                if ( $arrService.Status -eq "Running" ) {
                Write-Host "Service "$ServiceName" exists, and is running!"
                Write-Host ""
                $Return = $True
                }else{
                Write-Host "Service "$ServiceName" exists, but is not running!"
                Write-Host ""
                }
                }else{
                Write-Host "Service "$ServiceName" does not exist!"
                Write-Host ""
                }
                Return $Return
                }


                # -------
                # PROGRAM
                # -------

                if(ProcessRunning("Docker for Windows")){
                Write-Host "Docker is running"
                Write-Host ""
                docker version
                }else{
                Write-Host "Docker is not running"
                Write-Host ""
                Write-Host "Starting Docker"
                Write-Host ""
                Start-Process $DockerPath

                #Waits while Docker has not finished starting up
                $dockerStarting = $true
                while($dockerStarting){
                if((ServiceRunning("com.docker.service")) -and (ServiceRunning("docker"))){
                Write-Host ""
                Write-Host "Docker has finished starting up!"
                Write-Host ""
                docker version
                $dockerStarting = $false
                }else{
                Write-Host ""
                Write-Host "Docker is still starting up..."
                Write-Host ""

                #Attempts to start the relevant services
                if(!(ServiceRunning("com.docker.service"))){
                if(ServiceExists("com.docker.service")){
                Start-Service "com.docker.service"
                }
                }
                if(!(ServiceRunning("docker"))){
                if(ServiceExists("docker")){
                Start-Service "docker"
                }
                }

                $dockerStarting = $true
                Wait-Event -Timeout $TimeoutInterval
                }
                }
                }


                I still have no idea why try-catch isn't working in TeamCity, so if someone knows the answer to that, please comment.



                Anyway, I hope this solution is helpful to someone.






                share|improve this answer












                Okay, so I tried around a lot, and eventually found a solution that allows me to check if Docker is running via a TeamCity build step and successfully start it if not.



                This actually turned out to be a two-tier problem, with two separate things having to be done in order to make it work:



                1.) Run the TeamCity Build Agent Service as an elevated local account



                In my case, I had the TeamCity Build Agent Service running under the SYSTEM account. I switched it to an Administrator account using:



                Services
                ↳TeamCity Build Agent
                ↳Log On>Log on as
                ↳◉This account: .Administrator


                2.) Use a "clean" skript that does not rely on try-catch to see if Docker is running



                The final PowerShell Skript that I'm using now and that works nicely looks like this:



                # 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 FilesDockerDockerDocker for Windows.exe"


                # ---------
                # FUNCTIONS
                # ---------

                Function ProcessRunning([string] $ProcessName) {
                [bool] $Return = $False
                if ( Get-Process | Where-Object {$_.Name -like $ProcessName} ) {
                $Return = $True
                }
                Return $Return
                }

                # Determines if a Service exists with a name as defined in $ServiceName.
                Function ServiceExists([string] $ServiceName) {
                [bool] $Return = $False
                if ( Get-Service "$ServiceName*" -Include $ServiceName ) {
                $Return = $True
                }
                Return $Return
                }

                # Determines if a Service with a name as defined in $ServiceName exists and is running
                Function ServiceRunning([string] $ServiceName) {
                [bool] $Return = $False
                Write-Host "Checking if Service "$ServiceName" exists and is running"
                Write-Host ""
                if ( Get-Service "$ServiceName*" -Include $ServiceName ) {

                $arrService = Get-Service -Include $ServiceName

                if ( $arrService.Status -eq "Running" ) {
                Write-Host "Service "$ServiceName" exists, and is running!"
                Write-Host ""
                $Return = $True
                }else{
                Write-Host "Service "$ServiceName" exists, but is not running!"
                Write-Host ""
                }
                }else{
                Write-Host "Service "$ServiceName" does not exist!"
                Write-Host ""
                }
                Return $Return
                }


                # -------
                # PROGRAM
                # -------

                if(ProcessRunning("Docker for Windows")){
                Write-Host "Docker is running"
                Write-Host ""
                docker version
                }else{
                Write-Host "Docker is not running"
                Write-Host ""
                Write-Host "Starting Docker"
                Write-Host ""
                Start-Process $DockerPath

                #Waits while Docker has not finished starting up
                $dockerStarting = $true
                while($dockerStarting){
                if((ServiceRunning("com.docker.service")) -and (ServiceRunning("docker"))){
                Write-Host ""
                Write-Host "Docker has finished starting up!"
                Write-Host ""
                docker version
                $dockerStarting = $false
                }else{
                Write-Host ""
                Write-Host "Docker is still starting up..."
                Write-Host ""

                #Attempts to start the relevant services
                if(!(ServiceRunning("com.docker.service"))){
                if(ServiceExists("com.docker.service")){
                Start-Service "com.docker.service"
                }
                }
                if(!(ServiceRunning("docker"))){
                if(ServiceExists("docker")){
                Start-Service "docker"
                }
                }

                $dockerStarting = $true
                Wait-Event -Timeout $TimeoutInterval
                }
                }
                }


                I still have no idea why try-catch isn't working in TeamCity, so if someone knows the answer to that, please comment.



                Anyway, I hope this solution is helpful to someone.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 23 at 9:44









                Kira Resari

                478




                478






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53371823%2fteamcity-start-docker-on-server-via-build-step%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Costa Masnaga

                    Fotorealismo

                    Sidney Franklin