Skip to content

Instantly share code, notes, and snippets.

@jkroepke
Last active June 7, 2023 10:07
Show Gist options
  • Save jkroepke/bd2cde0aad4f9c6daed5c78ca6892905 to your computer and use it in GitHub Desktop.
Save jkroepke/bd2cde0aad4f9c6daed5c78ca6892905 to your computer and use it in GitHub Desktop.
setup.ps1
# https://karask.com/retry-powershell-invoke-webrequest
function Invoke-WebRequestRetry {
Param(
[Parameter(Mandatory=$True)][hashtable]$Params,
[int]$Retries = 3,
[int]$SecondsDelay = 2
)
if ($Params.ContainsKey('Method')) {
$method = $Params['Method']
} else {
$method = "GET"
}
if ($Params.ContainsKey('OutFile')) {
$Params['Passthru'] = $true
}
$Params['UseBasicParsing'] = $true
$url = $Params['Uri']
$cmd = { Write-Host "$method $url ..."; Invoke-WebRequest @Params }
$retryCount = 0
$completed = $false
$response = $null
while (-not $completed) {
try {
$response = Invoke-Command $cmd -ArgumentList $Params
if ($response.StatusCode -ne 200) {
throw "Expecting reponse code 200, was: $($response.StatusCode)"
}
$completed = $true
} catch {
if ($retrycount -ge $Retries) {
Write-Host "Request to $url failed the maximum number of $retryCount times."
Write-Host $_
throw
} else {
Write-Host "Request to $url failed. Retrying in $SecondsDelay seconds."
Write-Host $_
Start-Sleep $SecondsDelay
$retrycount++
}
}
}
Write-Host "OK ($($response.StatusCode))"
return $response
}
function AuthBasicHeader() {
Param(
[Parameter(Mandatory=$True)][string]$username,
[Parameter(Mandatory=$True)][string]$password
)
$pair = "$($username):$($password)"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$basicAuthValue = "Basic $encodedCreds"
return @{
Authorization = $basicAuthValue
}
}
function CleanupFiles() {
Write-Host "Cleanup setup files..."
Remove-Item -Force "$tmpDir\grafana-agent-setup.exe.zip","$setupFilePath" -ea 0 | Out-Null
}
###################################
### COMMON POWERSHELL FOO START ###
###################################
# https://stackoverflow.com/a/44810914/8087167
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$VerbosePreference = "SilentlyContinue"
$PSDefaultParameterValues['*:ErrorAction']='Stop'
# https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/debug-customscriptextension-runcommand-scripts
Start-Transcript -Path "$env:SystemRoot\Temp\PowerShell_transcript.$($env:COMPUTERNAME).$(Get-Date ((Get-Date).ToUniversalTime()) -f yyyyMMddHHmmss).txt" -IncludeInvocationHeader
Set-PSDebug -Trace 0
Trap { CleanupFiles }
#######################################
### DEFINE URL FOR REMOTE RESOURCES ###
#######################################
$authHeaders = AuthBasicHeader "foo" "bar"
$imdsResourceIdUrl = "http://169.254.169.254/metadata/instance/compute/resourceId?api-version=2021-02-01&format=text"
$setupUrl = "https://github.com/grafana/agent/releases/download/v0.34.0-rc.2/grafana-agent-flow-installer.exe.zip"
$mainConfigUrl = "https://raw.githubusercontent.com/jkroepke/homelab/main/grafana-agent/flow-remote-configuration/main.river"
$grafanaAgentUrl = "http://127.0.0.1:12345/-/reload"
# https://github.com/grafana/agent/blob/main/packaging/grafana-agent-flow/windows/install_script.nsis#L27
$installDir = "C:\Program Files\Grafana Agent Flow"
$tmpDir = "$env:SystemRoot\Temp"
$setupFilePath = "$tmpDir\grafana-agent-flow-installer.exe"
##################################
### FETCH VM ID FOR USER AGENT ###
##################################
Write-Host "Get VM ResourceID from IMDS."
$vmResourceIdResponse = Invoke-WebRequestRetry -Params @{ 'Uri' = $imdsResourceIdUrl; 'Headers' = @{ 'Metadata' = 'true' } }
$vmResourceId = $vmResourceIdResponse.Content
##################################
### FETCH SETUP FROM OPS.STACK ###
##################################
Invoke-WebRequestRetry -Params @{ 'Uri' = $setupUrl; 'Headers' = $authHeaders; 'UserAgent' = $vmResourceId; 'OutFile' = "$tmpDir\grafana-agent-setup.exe.zip"} | Out-Null
########################
### EXTRACT ZIP FILE ###
########################
Write-Host "Extract $tmpDir\grafana-agent-setup.exe.zip"
Expand-Archive -Force "$tmpDir\grafana-agent-setup.exe.zip" -DestinationPath $tmpDir | Out-Null
#################################
### START GRAFANA AGENT SETUP ###
#################################
Write-Host "Start $tmpDir\grafana-agent-setup.exe"
# https://stackoverflow.com/a/7109778/8087167
$setup = Start-Process -Wait -FilePath "$setupFilePath" -ArgumentList "/S" -PassThru -NoNewWindow
if($setup.ExitCode -ne 0)
{
throw "Installation process returned error code: $($p.ExitCode)"
}
#####################################
### DOWNLOAD GRAFANA AGENT CONFIG ###
#####################################
# https://github.com/grafana/agent/blob/4d8d16fff1f762e6d1b365fb60c635c98c94afb7/packaging/grafana-agent-flow/windows/install_script.nsis#L88-L93
Invoke-WebRequestRetry -Params @{ 'Uri' = $mainConfigUrl; 'Headers' = $authHeaders; 'UserAgent' = $vmResourceId; 'OutFile' = "$($installDir)\config.river" } | Out-Null
##########################################
### RELOAD AND VALIDATE GRAFANA AGENT ###
##########################################
Write-Host "Reload grafana-agent and validate, if the Agent is up and running."
Invoke-WebRequestRetry -Params @{ 'Uri' = $grafanaAgentUrl; 'Method' = 'POST' } | Out-Null
#########################
### CLEANUP TMP FILES ###
#########################
CleanupFiles
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment