Auto-Start Self-Hosted Azure DevOps Agent After Restart

Talha Rashid 20 Reputation points
2025-03-17T15:56:06.57+00:00

We have a self hosted agent running our builds. We have configured it to auto shutdown everyday. In the morning, we always have to go and run the pipeline agent. Is there a way we can make it run everyday, especially each time we do the restart?

Azure DevOps
0 comments No comments
{count} votes

Accepted answer
  1. Damilola Onadeinde 475 Reputation points
    2025-03-17T16:45:47.95+00:00

    You can have this done by enabling this two flags in your self-hosted agent command/script.

    • --runAsService: Configures the agent to run as a service.
    • --runAsAutoLogon: runs the agent each time after restarting the machine.

    In one of my previous project. Here is the script I built specifically for this purpose.

    # Define variables
    $AgentPackageUrl = "https://vstsagentpackage.azureedge.net/agent/3.238.0/vsts-agent-win-x64-3.238.0.zip"
    $AgentPackagePath = "$env:TEMP\agent.zip"
    $AgentExtractPath = "C:\agent"
    
    # Set Azure DevOps organization URL
    $OrganizationUrl = "https://dev.azure.com/dammyboss" 
    
    # Set Personal Access Token 
    $PAT = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    
    # Set agent name
    $AgentName = "xxx"
    
    # Set pool name
    $PoolName = "xxxxxx"
    
    # Download agent package
    Invoke-WebRequest -Uri $AgentPackageUrl -OutFile $AgentPackagePath
    
    # Extract agent package
    Expand-Archive -Path $AgentPackagePath -DestinationPath $AgentExtractPath
    
    # Navigate to agent directory
    Set-Location -Path $AgentExtractPath
    
    # Run configuration script with parameters
    & .\config.cmd --url $OrganizationUrl --token $PAT --pool $PoolName --agent $AgentName --unattended
    

    In this script, I have added the necessary flags to run as a service and restart at logon. You would not have to worry about having to log in to the machine to start the agent.

    I took the liberty to test this on one of my VMs just a few mins ago, see the result below. I restarted it and confirmed the service start running post restart.

    User's image User's image

    User's image

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.