Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save darinpope/a69530c07f6bd45dac2384710d74368f to your computer and use it in GitHub Desktop.
Save darinpope/a69530c07f6bd45dac2384710d74368f to your computer and use it in GitHub Desktop.

Gist for https://youtu.be/N8AQTlHoBKc

Documentation

Sample service.xml

<service>
  <id>jenkins8080agent</id>
  <name>Jenkins Agent for jenkins:8080</name>
  <description>This service runs the agent process connected to jenkins:8080</description>
  <executable>D:\tools\jdk-11.0.15.10-hotspot\bin\java.exe</executable>
  <arguments>-jar D:\tools\jenkins-agent\agent.jar -jnlpUrl http://jenkins:8080/computer/windows/jenkins-agent.jnlp -secret b66b6def580864901a50b9c8daaeea96f9e7f5537f02eb58bf5f6d1deae4155c -workDir "d:\tools\jenkins-agent"</arguments>
  <log mode="roll" />
  <onfailure action="restart" />
    <serviceaccount>
    <domain>BETA-TWO</domain>
    <user>jenkinsagent</user>
    <password>Password123</password>
    <allowservicelogon>true</allowservicelogon>
  </serviceaccount>
</service>
@Dikkekip
Copy link

Dikkekip commented Jul 4, 2023

Do this installation in powershell

param(
    [string]$jenkinsUrl = "http://yourjenkinsserver.com",
    [string]$jenkinsDir = "C:\Jenkins",
    [string]$vaultName = "YourKeyVaultName"
)

# Install PSFramework if it's not already installed
if (-not (Get-Module -ListAvailable -Name PSFramework)) {
    Write-Host "Installing PSFramework module..."
    Install-Module -Name PSFramework -Force
}

# Import PSFramework module
Import-Module -Name PSFramework

# Set logging path and create directory if it does not exist
$loggingPath = "$env:TEMP\jenkins_installation.log"
if (!(Test-Path -Path $env:TEMP)) {
    New-Item -ItemType Directory -Force -Path $env:TEMP
}
Set-PSFConfig -Module PSFramework -Name Provider.Filesystem.Logging.Path -Value $loggingPath -Initialize -PassThru

# Function to check if Azure CLI is installed
function CheckAzureCLI {
    $azcli = az --version
    if (-not $azcli) {
        Write-PSFMessage -Level Host -Message "Azure CLI not found. Installing via Chocolatey..."
        choco install azure-cli
    }
    else {
        Write-PSFMessage -Level Host -Message "Azure CLI found."
    }
}
$agentName = hostname

$secretName = "JenkinsAgent-$agentName"
# Call the CheckAzureCLI function
CheckAzureCLI

# Get the secret from Azure Key Vault
$secret = az keyvault secret show --name $secretName --vault-name $vaultName --query value -o tsv

# Add the System.Web assembly to use HttpUtility::UrlEncode
Add-Type -AssemblyName System.Web

# Set agent name to be the hostname of the server


# URL encode the agent name
$encodedAgentName = [System.Web.HttpUtility]::UrlEncode($agentName)

# Function to check if Java is installed
function CheckJava {
    $java = Get-Command java -ErrorAction SilentlyContinue
    if (-not $java) {
        Write-PSFMessage -Level Host -Message "Java not found. ??..."
    }
    else {
        Write-PSFMessage -Level Host -Message "Java found at $($java.Source)"
    }
}

# Call the CheckJava function
CheckJava

# Create Jenkins directory if it does not exist
if (!(Test-Path -Path $jenkinsDir)) {
    Write-PSFMessage -Level Host -Message "Jenkins directory not found. Creating directory..."
    New-Item -ItemType Directory -Force -Path $jenkinsDir
}

# Download the agent.jar file from the Jenkins server
Write-PSFMessage -Level Host -Message "Downloading Jenkins agent from $jenkinsUrl"
Invoke-WebRequest -Uri "$jenkinsUrl/jnlpJars/agent.jar" -OutFile "$jenkinsDir\agent.jar"

if (!(Test-Path -Path "$jenkinsDir/jenkins-slave.exe")) {
    # Download the agent executable
    Write-PSFMessage -Level Host -Message "Downloading Jenkins agent executable"
    # Define variables
    $repoOwner = "winsw"
    $repoName = "winsw"
    $latestReleaseUrl = "https://api.github.com/repos/$repoOwner/$repoName/releases/latest"


    # Get latest release information
    $latestRelease = Invoke-RestMethod -Uri $latestReleaseUrl
    $downloadUrl = ($latestRelease.assets | Where-Object { $_.name -eq "WinSW-x64.exe" }).browser_download_url

    # Download Windows Service Wrapper
    Invoke-WebRequest -Uri $downloadUrl -OutFile "$jenkinsDir/jenkins-slave.exe"

    # Output commands used
}

function GetJavaPath {
    $javaDirs = Get-ChildItem -Path 'C:\Program Files\Java\' -ErrorAction SilentlyContinue
    $javaDirs = $javaDirs | Where-Object { $_ -match 'jdk' } # Filter for JDK directories
    if ($javaDirs.Count -eq 0) {
        # No Java found in the default directory, check PATH
        $javaPath = (Get-Command -CommandType Application java -ErrorAction SilentlyContinue).Source
    }
    else {
        # Multiple Java versions found, use the latest one
        $latestJavaDir = $javaDirs | Sort-Object -Descending | Select-Object -First 1
        $javaPath = "C:\Program Files\Java\$latestJavaDir\bin\java.exe"
    }

    if (-not $javaPath) {
        Write-PSFMessage -Level Host -Message "Java not found. Installing via Chocolatey..."
        exit 1
    }

    return $javaPath
}

# Get the path to the Java executable
$javaPath = GetJavaPath
Write-PSFMessage -Level Host -Message "Java found at $javaPath"


# Generate the agent.xml file
$configXML = @"
<service>
  <id>$agentName</id>
  <name>Jenkins local service agent</name>
  <description>This service runs a local agent executor for Jenkins server.</description>
  <executable>$javaPath</executable>
  <arguments>-jar "$jenkinsDir\agent.jar" -jnlpUrl $jenkinsUrl/computer/$encodedAgentName/jenkins-agent.jnlp -secret $secret -workDir "$jenkinsDir"</arguments>
  <logmode>rotate</logmode>
  <onfailure action="restart" />
  <extensions>
    <extension enabled="true" className="winsw.Plugins.RunawayProcessKiller.RunawayProcessKillerExtension" id="killOnStartup">
	   <pidfile>$jenkinsDir\jenkins_agent.pid</pidfile>
      <stopTimeout>5000</stopTimeout>
      <stopParentFirst>false</stopParentFirst>
    </extension>
  </extensions>
</service>
"@

# Write the agent.xml file to disk
$configXML | Out-File -FilePath "$jenkinsDir\jenkins-slave.xml"

# Install the Jenkins agent service using the executable
Write-PSFMessage -Level Host -Message "Creating Jenkins agent service"
# Install Windows Service Wrapper as a service
& $jenkinsDir\jenkins-slave.exe install
& $jenkinsDir\jenkins-slave.exe start

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment