-
Notifications
You must be signed in to change notification settings - Fork 36
/
kubernetesHelper.ps1
436 lines (379 loc) · 13.8 KB
/
kubernetesHelper.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
if ($deployHelpLoaded -eq $null)
{
$DeployToolsDir = Split-Path ((Get-Variable MyInvocation -Scope 0).Value.MyCommand.Path)
. $DeployToolsDir\deployHelp.ps1
}
Write-Host "Ensconce - KubernetesHelper Loading"
if ([string]::IsNullOrWhiteSpace($KubeCtlExe))
{
$KubeCtlExe = "$DeployToolsDir\Tools\KubeCtl\kubectl.exe"
}
if ([string]::IsNullOrWhiteSpace($KubeLinterExe))
{
$KubeLinterExe = "$DeployToolsDir\Tools\Kube-Linter\kube-linter.exe"
}
$rootConfigPath = "$Home\.kube"
if (Test-Path $KubeCtlExe)
{
(& $KubeCtlExe version --output=json --client 2>&1) | ForEach-Object {
if ($_ -match "^Client Version.*")
{
$data = ConvertFrom-Json ($_ -replace "Client Version: version.Info", "")
$clientVersion = $data.GitVersion
Write-Host "KubeCtl Version: $clientVersion"
}
}
}
else
{
throw "'$KubeCtlExe' doesn't exist"
}
if (Test-Path $KubeLinterExe)
{
$kubeLinterVersion = (& $KubeLinterExe version 2>&1)
Write-Host "Kube-Linter Version: $kubeLinterVersion"
$KubeLinterExeFound = $true
}
else
{
Write-Warning "Kube-Linter exe not found at $KubeLinterExe"
$KubeLinterExeFound = $false
}
function PreProcessYaml([string]$yamlDirectory)
{
if ((Test-Path -Path "$yamlDirectory\kustomization.yaml") -eq $false)
{
Write-Host "Creating kustomization.yaml"
Add-Content -Path "$yamlDirectory\kustomization.yaml" -Value "resources:"
Get-ChildItem "$yamlDirectory" -Filter *.yaml | Foreach-Object {
if ($_.Name -ne "kustomization.yaml")
{
Add-Content -Path "$yamlDirectory\kustomization.yaml" -Value " - $($_.Name)"
}
}
}
if ([string]::IsNullOrWhiteSpace($KustomizeTemplatesFolder) -eq $false -and (Test-Path $KustomizeTemplatesFolder))
{
Write-Host "Copying templates from $KustomizeTemplatesFolder into $yamlDirectory\templates"
Copy-Item -Path $KustomizeTemplatesFolder -Destination "$yamlDirectory\templates" -Recurse | Out-Null
}
Get-ChildItem -Path $yamlDirectory -Filter "*substitution*.xml" -Recurse | ForEach-Object {
Write-Host "Processing Subsitution: $($_.FullName)"
ensconce --deployFrom $yamlDirectory --updateConfig --substitutionPath $_.FullName | Write-Host
}
if ([string]::IsNullOrWhiteSpace($ScriptDir) -eq $false)
{
Get-ChildItem -Path $ScriptDir -Filter "*substitution*.xml" | ForEach-Object {
Write-Host "Processing Subsitution: $($_.FullName)"
ensconce --deployFrom $ScriptDir --updateConfig --substitutionPath $_.FullName | Write-Host
}
}
Write-Host "Replace tags in yaml in $yamlDirectory"
ensconce --deployFrom $yamlDirectory --treatAsTemplateFilter=*.yaml | Write-Host
Write-Host "Replace tags in json in $yamlDirectory"
ensconce --deployFrom $yamlDirectory --treatAsTemplateFilter=*.json | Write-Host
Get-ChildItem -Path $yamlDirectory -Filter "*.*" -File -Recurse | ForEach-Object {
Write-Host "Update Encoding To UTF-8 Without BOM: $($_.FullName)"
$MyRawString = Get-Content -Raw $_.FullName
$Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False
[System.IO.File]::WriteAllLines($_.FullName, $MyRawString, $Utf8NoBomEncoding)
}
Write-Host "Running kustomize in $yamlDirectory"
$outputFile = "$yamlDirectory\kustomization-output.yaml"
& $KubeCtlExe kustomize $yamlDirectory --output $outputFile
if ($LASTEXITCODE -ne 0)
{
Write-Error "Kustomize error processing $kustomizationPath"
exit $LASTEXITCODE
}
$outputFile
}
function ValidateK8sYaml([string]$yamlFile, [string]$kubernetesConfigFile)
{
if($KubeLinterExeFound)
{
$KubeLinterConfigYamlFile = [IO.Path]::Combine((Split-Path -Path $yamlFile), "kube-linter-config.yaml")
if(Test-Path $KubeLinterConfigYamlFile)
{
Remove-Item $KubeLinterConfigYamlFile -Force
}
if([string]::IsNullOrWhiteSpace($KubeLinterConfigYaml) -eq $false)
{
$KubeLinterConfigYaml | Out-File -FilePath $KubeLinterConfigYamlFile
}
Write-Host "Validating yaml file $yamlFile (kube-linter)"
$ErrorActionPreferenceOrig = $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
if(Test-Path $KubeLinterConfigYamlFile)
{
$kubeLinterOutput = & $KubeLinterExe lint $yamlFile --fail-if-no-objects-found --fail-on-invalid-resource --format json --config $KubeLinterConfigYamlFile 2>&1
}
else
{
$kubeLinterOutput = & $KubeLinterExe lint $yamlFile --fail-if-no-objects-found --fail-on-invalid-resource --format json 2>&1
}
$ErrorActionPreference = $ErrorActionPreferenceOrig
$kubeLinterData = ConvertFrom-Json $kubeLinterOutput
if ($LASTEXITCODE -ne 0 -or $kubeLinterData.Summary.ChecksStatus -eq "Failed")
{
$FailureCount = 0
$ErrorTable = @()
$kubeLinterData.Reports | ForEach-Object {
$ErrorTable += [PSCustomObject] @{
Name = $_.Object.K8sObject.Name
Kind = $_.Object.K8sObject.GroupVersionKind.Kind
Check = $_.Check
Message = $_.Diagnostic.Message
Remediation = $_.Remediation
Docs = "https://docs.kubelinter.io/#/generated/checks?id=$($_.Check)"
Full = $_
}
$FailureCount++
}
Write-Host
Write-Host "--------------------------------------"
Write-Host "Failures Report"
Write-Host "_______________"
$ErrorTable | Format-Table -Wrap -AutoSize -GroupBy @{name = "Failure Object"; expr = {"$($_.Name) ($($_.Kind))"}} -Property Check, Message, Docs
Write-Host "--------------------------------------"
Write-Host
$KubeLinterFailureMessage = "$FailureCount Errors for yaml file $yamlFile (kube-linter)"
if($KubeLinterFailureMode -eq "LOG")
{
$KubeLinterFailureMessage | Write-Host
}
else
{
if($KubeLinterFailureMode -eq "WARN")
{
$KubeLinterFailureMessage | Write-Warning
}
else
{
$KubeLinterFailureMessage | Write-Error
exit $LASTEXITCODE
}
}
}
else
{
Write-Host "No errors for yaml file $yamlFile (kube-linter)"
}
}
$kubernetesConfigFilePath = "$rootConfigPath\$kubernetesConfigFile"
Write-Host "Validating yaml file $yamlFile (local)"
& $KubeCtlExe apply --dry-run=client -f $yamlFile --kubeconfig=$kubernetesConfigFilePath
if ($LASTEXITCODE -ne 0)
{
if($KubeCtlFailOnDryRun -eq $false)
{
Write-Warning "Invalid yaml file $yamlFile (local)"
}
else
{
Write-Error "Invalid yaml file $yamlFile (local)"
exit $LASTEXITCODE
}
}
else
{
Write-Host "Valid yaml file $yamlFile (local)"
}
Write-Host "Validating yaml file $yamlFile (server-side)"
& $KubeCtlExe apply --dry-run=server -f $yamlFile --kubeconfig=$kubernetesConfigFilePath
if ($LASTEXITCODE -ne 0)
{
if($KubeCtlFailOnDryRun -eq $false)
{
Write-Warning "Invalid yaml file $yamlFile (server-side)"
}
else
{
Write-Error "Invalid yaml file $yamlFile (server-side)"
exit $LASTEXITCODE
}
}
else
{
Write-Host "Valid yaml file $yamlFile (server-side)"
}
}
function SetK8sContext([string]$kubernetesConfigFile)
{
$kubernetesConfigFilePath = "$rootConfigPath\$kubernetesConfigFile"
$targetContext = "k8s-cluster"
Write-Host "Getting current context"
$currentContext = & $KubeCtlExe config current-context --kubeconfig=$kubernetesConfigFilePath
if ($LASTEXITCODE -ne 0)
{
Write-Error "Error getting current kubernetes context"
exit $LASTEXITCODE
}
if ($currentContext -ne $targetContext)
{
Write-Host "Switching from '$currentContext' context to '$targetContext' context"
& $KubeCtlExe config use-context "$targetContext" --kubeconfig=$kubernetesConfigFilePath
if ($LASTEXITCODE -ne 0)
{
Write-Error "Error setting kubernetes context to '$targetContext'"
exit $LASTEXITCODE
}
}
else
{
Write-Host "Already working with '$targetContext' context"
}
}
function GetResourceVersionsUsed([string]$kubernetesConfigFile, [string]$selector)
{
Write-Host "Get Accessible Resources"
$resourceVersions = @()
$resources = @()
$knownResourcesArray = @()
if($knownResources -ne $null)
{
$knownResourcesArray = $knownResources.Split(",",[System.StringSplitOptions]::RemoveEmptyEntries)
}
$rawResources = & $KubeCtlExe api-resources --verbs=list --namespaced -o name --kubeconfig=$kubernetesConfigFilePath
if ($LASTEXITCODE -ne 0)
{
Write-Error "Error all api resources"
exit $LASTEXITCODE
}
if($knownResourcesArray.Count -ne 0)
{
Write-Host "Known Resource Types: $knownResourcesArray"
}
foreach($resource in $rawResources)
{
if ($resource.Contains("."))
{
$resource = $resource.Substring(0, $resource.IndexOf("."))
}
if (($knownResourcesArray.Count -eq 0) -or ($knownResourcesArray -contains $resource))
{
if ($resources -notcontains $resource)
{
$cani = & $KubeCtlExe auth can-i list $resource --kubeconfig=$kubernetesConfigFilePath
if ($LASTEXITCODE -eq 0 -and $cani -eq "yes")
{
Write-Host " * $resource (accessible)"
$resources += $resource
}
else
{
Write-Host " * $resource (not accessible)"
}
}
}
else
{
Write-Host " * $resource (not checked)"
}
}
if ($resources.Count -gt 0)
{
Write-Host "Accessible Server Resources: $resources"
Write-Host "Getting Resources Used On Selector: $selector"
foreach($resource in $resources)
{
Write-Host " Getting: $resource"
$output = & $KubeCtlExe get $resource -l $selector -o json --kubeconfig=$kubernetesConfigFilePath | ConvertFrom-Json
if ($LASTEXITCODE -ne 0)
{
Write-Error "Error getting $resource"
exit $LASTEXITCODE
}
foreach($item in $output.items)
{
$groupVersion = $item.apiVersion
if (-not($groupVersion.Contains("/")))
{
$groupVersion = "core/${groupVersion}"
}
$kind = $item.kind
$GroupVersionKind = "${groupVersion}/${kind}"
if ($resourceVersions -notcontains $GroupVersionKind)
{
$resourceVersions += $GroupVersionKind
}
}
}
if ($resourceVersions.Count -gt 0)
{
Write-Host "Used API Versions: $resourceVersions"
}
else
{
Write-Host "No User API Versions"
}
}
else
{
Write-Host "No Accessible Server Resources"
}
$resourceVersions
}
function DeployToK8s([string]$yamlFile, [string]$kubernetesConfigFile, [string]$pruneSelector)
{
$kubernetesConfigFilePath = "$rootConfigPath\$kubernetesConfigFile"
$prunableList = GetResourceVersionsUsed $kubernetesConfigFile $pruneSelector
$deploymentName = ""
Write-Host "Deploying yaml file $yamlFile"
#Run using Invoke-Expression because of dynamic parameters
if ($prunableList.Count -gt 0)
{
$pruneWhiteList = $prunableList -join " --prune-allowlist="
$command = "$KubeCtlExe apply -f $yamlFile --prune -l $pruneSelector --prune-allowlist=$pruneWhiteList --kubeconfig=$kubernetesConfigFilePath"
}
else
{
$command = "$KubeCtlExe apply -f $yamlFile --kubeconfig=$kubernetesConfigFilePath"
}
Invoke-Expression $command | foreach-object {
Write-Host $_
if ($_.StartsWith("deployment.apps/"))
{
$deploymentLineName = $_.Substring(0, $_.IndexOf(' '))
if ($deploymentName -eq "")
{
$deploymentName = $deploymentLineName
}
else
{
Write-Warning "Second deployment detected in package with name $deploymentLineName - This will not be checked for rollout"
}
}
}
if ($LASTEXITCODE -ne 0)
{
Write-Error "Error applying yaml file $yamlFile"
exit $LASTEXITCODE
}
if ($deploymentName -eq "")
{
Write-Error "Unable to establish deployment name"
exit -1
}
For ($i=0; $i -lt 5; $i++) {
& $KubeCtlExe get $deploymentName --kubeconfig=$kubernetesConfigFilePath
if ($LASTEXITCODE -eq 0) {
break
}
Start-Sleep 5
}
& $KubeCtlExe rollout status $deploymentName --kubeconfig=$kubernetesConfigFilePath
if ($LASTEXITCODE -ne 0)
{
Write-Error "Rollout of $deploymentName was not successful"
exit $LASTEXITCODE
}
}
function DeployYamlFilesToK8sCluster([string]$yamlDirectory, [string]$kubernetesConfigFile, [string]$pruneSelector)
{
$yamlFile = PreProcessYaml $yamlDirectory
SetK8sContext $kubernetesConfigFile
ValidateK8sYaml $yamlFile $kubernetesConfigFile
DeployToK8s $yamlFile $kubernetesConfigFile $pruneSelector
}
Write-Host "Ensconce - KubernetesHelper Loaded"