-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKubernetesWindowsNodeHelpers.psm1
2325 lines (1937 loc) · 101 KB
/
KubernetesWindowsNodeHelpers.psm1
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
$ProgressPreference = 'SilentlyContinue'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls13
function AuthorizeSshPublicKey {
Param (
[Parameter(ValueFromPipeline)]
[Alias('i')]
[string] $PublicSshIdentityFile,
[Parameter(Position = 0, Mandatory)]
[string] $RemoteHost,
[Parameter(Position = 1, Mandatory)]
[string] $RemoteUsername,
[Parameter(Position = 2)]
[int] $Port = 22
)
Process {
Write-Host "Adding your SSH key to the SSH Agent is a convenient and more secure way to interact with SSH."
Write-Host "If you've already added your SSH key to the SSH Agent, you can answer 'N'."
Write-Host "If you're not sure if you've added your SSH key to the SSH agent, answer 'Y'. Your key will not be added twice."
Write-Host
$resp = Read-HostEx "Would you like to add your SSH key to the SSH Agent? [Y/n] (Default 'Y') " -ExpectedValue 'Y','n'
if (!$resp -or $resp -ieq 'y') {
Write-Host "Follow the on-screen prompts to add your SSH key to the SSH Agent."
Write-Host
$SshConfigPath = Join-Path (Join-Path $env:USERPRofile .ssh) config
if ((Test-Path $SshConfigPath)) {
$SshConfig = Get-Content $SshConfigPath -Raw
if ($SshConfig -inotmatch "(?m)^\s*Host\s+$RemoteHost\s*$") {
@'
Host k8s-master
AddKeysToAgent yes
IdentitiesOnly yes
'@ | Set-Content -Path $SshConfigPath
} else {
@'
Host k8s-master
AddKeysToAgent yes
IdentitiesOnly yes
'@ | Add-Content -Path $SshConfigPath
}
}
# Set the proper ACLs on the key file, or SSH won't let you copy it
icacls.exe $PublicSshIdentityFile /c /t /Inheritance:d
icacls.exe $PublicSshIdentityFile /c /t /Grant ${env:USERNAME}:F
icacls.exe $PublicSshIdentityFile /c /t /Remove Administrator "Authenticated Users" BUILTIN\Administrator BUILTIN Everyone System Users
ssh-add.exe $PublicSshIdentityFile
} else {
Write-Host
Read-HostEx "Whenever connecting to $RemoteHost via SSH, you will be prompted for your SSH key passphrase. [OK] "
Write-Host
}
Write-Host "Please follow the on-screen prompts to authorize your public SSH key on $RemoteHost."
Copy-SshKey -i $PublicSshIdentityFile $RemoteUsername $RemoteHost $Port
}
}
function ConfigureFirewall {
Param (
[switch] $Force
)
Process {
if (Get-NetFirewallProfile -Name 'Domain','Private','Public' | ForEach-Object -Begin { $Enabled = $False } -Process { $Enabled = $Enabled -or $_.Enabled } -End { $Enabled }) {
if (!($Force -and $Force.IsPresent)) {
Write-Host "One or more of the Domain, Private, or Public firewall profiles are enabled."
Write-Host "It is recommended to disable these firewall profiles."
$resp = Read-HostEx -Prompt "Disable the Domain, Private, and Public firewall profiles? [Y/n] (Default 'Y') " -ExpectedValue 'Y','n'
}
if (($Force -and $Force.IsPresent) -or !$resp -or $resp -ieq 'y') {
Set-NetFirewallProfile -Name 'Domain','Private','Public' -Enabled False
Write-Host "Disabled the Domain, Private and Public firewall profiles on this machine."
}
}
}
}
function DownloadAndExpandTarGzArchive {
Param (
[Parameter(Position = 0, Mandatory)]
[Uri] $Url,
[Parameter(Position = 1)]
[string] $DestinationPath = '.'
)
Process {
try {
$TgzFile = New-TemporaryFile
DownloadFile -Url $Url -Destination $TgzFile -Force
tar -xkf $TgzFile -C $DestinationPath
Remove-Item $TgzFile
} catch {
throw
}
}
}
function DownloadAndExpandZipArchive {
Param (
[Parameter(Position = 0, Mandatory)]
[Uri] $Url,
[Parameter(Position = 1)]
[string] $DestinationPath = '.'
)
Process {
$OriginalProgressPreference = $ProgressPreference
$ProgressPreference = 'SilentlyContinue'
try {
$ZipFile = New-TemporaryFile | Rename-Item -NewName { $_ -replace 'tmp$','zip' } -PassThru
DownloadFile -Url $Url -Destination $ZipFile -Force
Expand-Archive $ZipFile.FullName $DestinationPath
Remove-Item $ZipFile
} catch {
throw
} finally {
$ProgressPreference = $OriginialProgressPreference
}
}
}
function DownloadFile {
Param (
[Parameter(Position = 0, Mandatory, ValueFromPipeline)]
[Uri] $Url,
[Parameter(Position = 1)]
[string] $Destination,
[switch] $Force
)
Process {
if (!($Force -and $Force.IsPresent) -and $Destination -and (Test-Path $Destination)) {
Write-Host "[DownloadFile] File '$Destination' already exists."
return
}
try {
if (!$Destination) {
curl.exe -sL $Url | ForEach-Object -Begin { $result = New-Object System.Text.StringBuilder } -Process { $result = $result.AppendLine($_) } -End { $result.ToString() }
} else {
$Path = Split-Path $Destination -Parent
if ($Path -and !(Test-Path $Path)) {
$null = New-Item -ItemType Directory -Path $Path
}
curl.exe -sL $Url -o $Destination
Write-Host "Downloaded [$Url] => [$Destination]"
}
} catch {
Write-Error "Failed to download '$Url'"
throw
}
}
}
function LoadAndValidateKubernetesWindowsNodeConfiguration {
[OutputType('KubernetesWindowsNodeConfiguration')]
Param (
[Parameter(Position = 0)]
[string] $Path,
[switch] $Force
)
Process {
if ($Path -and (Test-Path $Path)) {
$Script:Config = Get-KubernetesWindowsNodeConfiguration -Path $Path -ErrorAction Stop
ValidateKubernetesWindowsNodeConfiguration -ErrorAction Stop
if ($Path -ine $Script:KuberenetesClusterNodeConfigurationPath -and !(Set-KubernetesWindowsNodeConfiguration $Script:KubernetesClusterNodeConfigurationPath -Force:$Force)) {
$resp = Read-HostEx "Do you want to read the existing configuration file? [Y/n] (Default 'Y') " -ExpectedValue 'Y','n'
if (!$resp -or $resp -ieq 'y') {
$Script:Config = Get-KubernetesWindowsNodeConfiguration
ValidateKubernetesWindowsNodeConfiguration -ErrorAction Stop
}
}
}
if (!$Script:Config) {
$Script:Config = Get-KubernetesWindowsNodeConfiguration -ErrorAction Stop
ValidateKubernetesWindowsNodeConfiguration -ErrorAction Stop
}
if (!$Script:Config) {
Write-Error "Unable to find existing kubernetes node configuration information at '$Script:KubernetesClusterNodeInstallationPath\.kubeclusterconfig'. Please supply a Kuberentes Cluster node configuration file."
}
}
}
function SetupSshAccessToControlPlane {
Param (
[string] $RemoteHost,
[string] $RemoteUsername,
[int] $Port = 22,
[switch] $Force
)
Process {
# If running interactively...
if (!($Force -and $Force.IsPresent)) {
Write-Host "While preparing this server to become a Kubernetes worker node, some configuration is required on $RemoteHost.
You will not be able to join this server to the cluster until $RemoteHost is configured. It is highly advised to setup
an SSH key that is authorized on $RemoteHost so that these configuration tasks can be performed by this script with
minimal intervention.
"
$resp = Read-HostEx "Would you like to authorize an SSH key on ${RemoteHost}? [Y|n] (Default 'Y') "
if (!$resp -or $resp -ieq 'y') {
# This is the default location for user identity files.
$PublicSshIdentityFile = Get-ChildItem "${env:USERPROFILE}\.ssh\*.pub" -File -ErrorAction SilentlyContinue
if ($PublicSshIdentityFile -and $PublicSshIdentityFile -is [Array]) {
$PublicSshIdentityFile = ''
}
if (!$PublicSshIdentityFile) {
Write-Host "Either an SSH key identity file was not found in '$env:USERPROFILE\.ssh', or more than one SSH key identity
file was found."
$resp = Read-HostEx "Do you want to specify the location of the identity file to use? [Y|n] (Default 'Y') " -ExpectedValue 'Y','n'
if ($resp -ieq 'y') {
Write-Host
Write-Host "Please provide the path and file name of the public SSH key identity file to use."
Write-Host "If you typed 'y' accidentally, please type 'QUIT' at the prompt to abort this process."
Write-Host
$PublicSshIdentityFile = Read-HostEx "Public SSH key identity file location" -ValueRequired
if ($PublicSshIdentityFile -ne 'QUIT') {
AuthorizeSshPublicKey -i $PublicSshIdentityFile $RemoteUsername $RemoteHost $Port -ErrorAction Stop
return
}
} else {
$resp = Read-HostEx "Would you like to create an SSH key now? [Y|n] (Default 'Y') "
if (!$resp -or $resp -ieq 'y') {
Write-Host "Please follow the on-screen prompts to generate a SSH public and private key pair."
ssh-keygen.exe
$PublicSshIdentityFile = Get-ChildItem "${env:USERPROFILE}\.ssh\*.pub" | Select-Object -First 1
AuthorizeSshPublicKey -i $PublicSshIdentityFile $RemoteUsername $RemoteHost $Port -ErrorAction Stop
return
}
}
} else {
# We found a public SSH key identity file. Ask if the user wants to:
# Add the key to the ssh-agent
# Authorize the key with the lunix conttrol plane
Write-Host "A SSH public key identity file was found at '$PublicSshIdentityFile'."
Write-Host
$resp = Read-HostEx "Would you like to authorize the public SSH key with ${RemoteHost}? [Y|n] (Default 'Y') "
if (!$resp -or $resp -ieq 'y') {
AuthorizeSshPublicKey -i $PublicSshIdentityFile $RemoteUsername $RemoteHost $Port -ErrorAction Stop
return
}
}
}
}
# >>>>>>>>> TODO: Fix getting module's path!!
Write-Host @"
Either you specified '-Force' when preparing this server as a Kubernetes cluster worker node, or you chose not to
create and/or authorize a SSH public/private key pair with $RemoteHost.
After this server has been prepared as a Kubernetes worker node, the following tasks must be completed before the
node can be joined to the cluster:
1. Import this script module:
PS C:\> Import-Module $($Script:MyInvocation.PSCommandPath)
2. Generate a public/private SSH key pair if you have not done so already.
PS C:\> ssh-keygen.exe
3. Optionally, but highly recommended, add your newly generated SSH key to the ssh-agent:
PS C:\> @'
Host $RemoteHost
AddKeysToAgent yes
IdentitiesOnly yes
'@ | Add-Content -Path $(Join-Path (Join-Path $env:USERPROFILE .ssh) config)
PS C:\> ssh-add.exe
4. Add $RemoteHost as a known host:
PS C:\> ssh-keyscan.exe $RemoteHost 2>`$null | Out-File $(Join-Path (Join-Path $env:USERPROFILE .ssh) known_hosts)
5. Add your SSH key as an authorized key on ${RemoteHost}:
PS C:\> Copy-SshKey -i $env:USERPROFILE\.ssh\id_rsa.pub $RemoteUsername $RemoteHost$(if ($Port -ne 22) { ":$Port" })
"@
pause
}
}
function ShouldBuildCustomFlannelDockerContainerImage {
[OutputType([boolean])]
Param (
[Parameter(Position = 0, Mandatory)]
[string] $FlannelVersion,
[Parameter(Position = 1)]
[ValidateSet('overlay','l2bridge')]
[string] $NetworkMode = 'overlay'
)
Process {
# Given the desired flannel version to use, and the network mode being employed
# in the Kubernetes cluster, determine whether or not a custom Flannel Docker
# container image will be required.
#
# The image in the DaemonSet defaults to Flannel 0.12.0. But, for example, this
# version is known to have a bug that is resolved in Flannel 0.13.0. So this is
# why someone may specify a different version of flannel--and the DaemonSet will
# then need to be updated.
$FlannelDaemonSetYamlUrl = "https://github.com/kubernetes-sigs/sig-windws-tools/raw/master/kubeadm/flannel/flannel-$(if ($NetworkMode -ieq 'overlay') { 'overlay' } else { 'host-gw' }).yml"
$FlannelDaemonSetYml = (Split-Path $FlannelDaemonSetYamlUrl -Leaf)
try {
curl.exe -sLO $FlannelDaemonSetYamlUrl
(Get-Content $FlannelDaemonSetYml -Raw -ErrorAction Stop) -match '(?m)sigwindowstools/flannel:(?<Version>\d+\.\d+\.\d+)$'
$FlannelVersion -ne $Matches.Version
} finally {
Remove-Item $FlannelDaemonSetYml -Force -ErrorAction SilentlyContinue
}
}
}
# TODO: I try to be nice and fill in "reasonable" defaults, such as using Flannel for CNI
# when no CNI information is given. But really, should I? Why not just fail with
# errors? I mean, I have New-KubernetesWindowsNodeConfiguration cmdlet that can
# walk you through constructing a proper configuration object....
function ValidateKubernetesWindowsNodeConfiguration {
[CmdletBinding()]
Param ()
Begin {
[string[]] $Errors = @()
}
Process {
if (!$Script:Config.Kubernetes) {
$Errors += "'Kubernetes' section is missing in the configuration file!"
} else {
if (!$Script:Config.Kubernetes.ControlPlane) {
$Errors += "'Kubernetes.ControlPlane' section is missing in the configuration file!"
}
if (!$Script:Config.PSObject.TypeNames -contains 'KubernetesClusterNodeConfiguration') {
$Script:Config.PSObject.TypeNames.Add('KubernetesClusterNodeConfiguration')
}
if (!$Script:Config.Kubernetes.Version) {
$Script:Config.Kubernetes = $Script:Config.Kubernetes | Add-Configuration 'Version' '1.19.3' -Force
Write-Host "'Kubernetes.Version' was not specified. Using 'v$($Script:Config.Kubernetes.Version)'".
}
if (!$Script:Config.Node.InterfaceName) {
$Script:Config.Node | Add-Configuration 'InterfaceName' 'Ethernet' -Force
$Script:Config.Node | Add-Configuration 'IPAddress' (Get-InterfaceIPAddress -InterfaceName $InterfaceName) -Force
$Script:Config.Node | Add-Configuration 'Subnet' (Get-InterfaceSubnet -InterfaceName $InterfaceName) -Force
$Script:Config.Node | Add-Configuration 'DefaultGateway' (Get-InterfaceDefaultGateway -InterfaceName $InterfaceName) -Force
Write-Host "'Node.InterfaceName' was not specified. Using '$($Script:Config.Node.InterfaceName)'."
}
if (!$Script:Config.Cri) {
$Script:Config | Add-Configuration 'Cri' ([PSCustomObject]@{ Name = 'dockerd' }) -Force
Write-Host "'Cri.Name' was not specified. Using '$($Script:Config.Cri.Name)'."
}
if (!$Script:Config.Cni) {
$Script:Config | Add-Configuration 'Cni' ([PSCustomObject]@{
NetworkMode = 'overlay'
NetworkName = 'vxlan0'
Version = '0.8.7'
Plugin = [PSCustomObject]@{
Name = $CniPluginName # e.g. flannel, kubenet
Version = $CniPluginVersion.ToLower().TrimStart('v')
InstallPath = $CniPluginInstallPath
}
}) -Force
Write-Host "The 'Cni' section was not specified. Using the following settings:`r`n`r`n$($Script:Config.Cni | ConvertTo-JSON)`r`n"
}
if (!$Script:Config.Cni.NetworkMode) {
$Errors += 'Missing ''Cni.NetworkMode'' configuration setting. Must be one of ''l2bridge'' or ''overlay''.'
}
if (!$Script:Config.Cni.Version) {
$Script:Config.Cni | Add-Configuration 'Version' '0.8.7' -Force
Write-Host "'Cni.Version' was not specified. Using 'v$($Script:Config.Cni.Version)'."
}
if (!$Script:Config.Cni.Plugin) {
if ($Script:Config.Cni.NetworkMode -iin 'overlay','l2bridge') {
$Script:Config.Cni | Add-Configuration 'Plugin' ([PSCustomObject]@{
Name = 'flannel'
Version = '0.13.0'
WindowsDaemonSetUrl = "https://raw.githubusercontent.com/kubernetes-sigs/sig-windows-tools/master/kubeadm/flannel/flannel-$(if ($Script:Config.NetworkMode -ieq 'overlay') { 'overlay' } else { 'host-gw' }).yml"
})
Write-Host "A 'Cni.Plugin' was not specified. Using '$($Script:Config.Cni.Plugin.Name) v$($Script:Config.Cni.Plugin.Version)'."
} else {
$Errors += 'Missing ''Cni.Plugin''.'
}
}
if (!$Script:Config.Cni.Plugin.Name) {
$Errors += 'Missing ''Cni.Plugin.Name''. Must be one of ''flannel'' or ''kubenet''.'
}
if ($Script:Config.Cni.Plugin.Name -eq 'flannel') {
if (!$Script:Config.Cni.Plugin.Version) {
$Script:Config.Cni.Plugin | Add-Configuration 'Version' '0.13.0'
Write-Host "A 'Cni.Plugin.Version' was not specified for '$($Script:Config.Cni.Plugin.Name)'. Using 'v$($Script:Config.Cni.Plugin.Version)'."
}
} else {
$Errors += 'Missing ''Cni.Plugin.Version''.'
}
if (!$Script:Config.Images) {
$Script:Config | Add-Configuration 'Images' ([PSCustomObject]@{
NanoServer = "mcr.microsoft.com/windows/nanoserver:$Script:WinVer"
ServerCore = "mcr.microsoft.com/windows/servercore:$Script:WinVer"
})
$Script:Config.Images | Add-Configuration 'Infrastructure' $(if ($Script:WinVer -notmatch '^10\.0\.17763') {
[PSCustomObject]@{
Build = $True
FlannelDockerfile = 'https://github.com/kubernetes-sigs/sig-windows-tools/raw/master/kubeadm/flannel/Dockerfile'
KubeProxyDockerfile = 'https://github.com/kubernetes-sigs/sig-windows-tools/raw/master/kubeadm/kube-proxy/Dockerfile'
PauseDockerfile = 'https://github.com/microsoft/SDN/raw/master/Kubernetes/windows/Dockerfile'
}
} elseif ($Script:Cni.Plugin.Name -eq 'flannel' -and (ShouldBuildCustomFlannelDockerContainerImage -FlannelVersion $Script:Config.Cni.Plugin.Version -NetworkMode $Script:Config.Cni.NetworkMode)) {
[PSCustomObject]@{
Build = $True
FlannelDockerfile = 'https://github.com/kubernetes-sigs/sig-windows-tools/raw/master/kubeadm/flannel/Dockerfile'
}
} else {
$InfrastructureImages = [PSCustomObject]@{
Build = $False
Pause = 'mcr.microsoft.com/oss/kubernetes/pause:1.3.0'
}
})
Write-Host 'An ''Images'' section was not found. Using the following images:'
Write-Host " Windows Nano Server: $($Script:Config.Images.NanoServer)"
Write-Host " Windows Server Core: $($Script:Config.Images.ServerCore)"
Write-Host " Infrastructure images:"
if ($Script:WinVer -notmatch '^10\.0\.17763') {
Write-Host " Custom images must be built because existing images don't support this version of Windows."
Write-Host " Flannel: $($Script:Config.Images.Infrastructure.FlannelDockerfile)"
Write-Host " Kube-Proxy: $($Script:Config.Images.Infrastructure.KubeProxyDockerfile)"
Write-Host " Pause: $($Script:Config.Images.Infrastructure.PauseDockerfile)"
} else {
Write-Host " Pause: $($Script:Config.Images.Infrastructure.Pause)"
}
}
if (!$Script:Config.Images.NanoServer) {
$Script:Config.Images | Add-Configuration 'NanoServer' "mcr.microsoft.com/windows/nanoserver:$Script:WinVer"
Write-Host "'Images.NanoServer' was not specified. Using '$($Script:Config.Images.NanoServer)'."
}
if (!$Script:Config.Images.ServerCore) {
$Script:Config.Images | Add-Configuration 'ServerCore' "mcr.microsoft.com/windows/servercore:$Script:WinVer"
Write-Host "'Images.ServerCore' was not specified. Using '$($Script:Config.Images.ServerCore)'."
}
if (!$Script:Config.Images.Infrastructure) {
$Script:Config.Images | Add-Configuration 'Infrastructure' $(if ($Script:WinVer -notmatch '^10\.0\.17763') {
[PSCustomObject]@{
Build = $True
FlannelDockerfile = 'https://github.com/kubernetes-sigs/sig-windows-tools/raw/master/kubeadm/flannel/Dockerfile'
KubeProxyDockerfile = 'https://github.com/kubernetes-sigs/sig-windows-tools/raw/master/kubeadm/kube-proxy/Dockerfile'
PauseDockerfile = 'https://github.com/microsoft/SDN/raw/master/Kubernetes/windows/Dockerfile'
}
} elseif ($Script:Cni.Plugin.Name -eq 'flannel' -and (ShouldBuildCustomFlannelDockerContainerImage -FlannelVersion $Script:Config.Cni.Plugin.Version -NetworkMode $Script:Config.Cni.NetworkMode)) {
[PSCustomObject]@{
Build = $True
FlannelDockerfile = 'https://github.com/kubernetes-sigs/sig-windows-tools/raw/master/kubeadm/flannel/Dockerfile'
}
} else {
$InfrastructureImages = [PSCustomObject]@{
Build = $False
Pause = 'mcr.microsoft.com/oss/kubernetes/pause:1.3.0'
}
})
Write-Host 'An ''Images.Infrastructure'' section was not found. Using the following images:'
Write-Host " Infrastructure images:"
if ($Script:WinVer -notmatch '^10\.0\.17763') {
Write-Host " Custom images must be built because existing images don't support this version of Windows."
Write-Host " Flannel: $($Script:Config.Images.Infrastructure.FlannelDockerfile)"
Write-Host " Kube-Proxy: $($Script:Config.Images.Infrastructure.KubeProxyDockerfile)"
Write-Host " Pause: $($Script:Config.Images.Infrastructure.PauseDockerfile)"
} else {
Write-Host " Pause: $($Script:Config.Images.Infrastructure.Pause)"
}
}
if (!$Script:Config.Kubernetes.Network) {
$Script:Config.Kubernetes | Add-Configuration 'Network' ([PSCustomObject]@{
ClusterCIDR = '10.244.0.0/16'
ServiceCIDR = '10.96.0.0/12'
DnsServiceIPAddress = '10.96.0.10'
})
Write-Host '''Kubernetes.Network'' was not specified. Using the following network settings:'
Write-Host " Cluster CIDR: $($Script:Config.Kubernetes.Network.ClusterCIDR)"
Write-Host " Service CIDR: $($Script:Config.Kubernetes.Network.SerivceCIDR)"
Write-Host " DNS Service IP Address: $($Script:Config.Kubernetes.Network.DnsServiceIPAddress)`r`n"
}
if (!$Script:Config.Kubernetes.Network.ClusterCIDR) {
$Errors += 'Missing ''Kubernetes.Network.ClusterCIDR''.'
}
if (!$Script:Config.Kubernetes.Network.ServiceCIDR) {
$Errors += 'Missing ''Kubernetes.Network.ServiceCIDR''.'
}
if (!$Script:Config.Kubernetes.Network.DnsServiceIPAddress) {
$Errors += 'Missing ''Kubernetes.Network.DnsServiceIPAddress''.'
}
if (!$Script:Config.Wins) {
$Script:Config | Add-Configuration 'Wins' ([PSCustomObject]@{ Version = 'latest' })
Write-Host '''Wins.Value'' was not specifified. Using version ''latest'' of Wins.'
}
}
}
End {
if ($Errors.Length -gt 0) {
throw "Errors were encountered while validating the Kubernetes Node Configuration file:`r`n$($Errors | ForEach-Object { " $_" })"
}
}
}
function WaitForNetwork {
Param (
[Parameter(Position = 0)]
[string] $NetworkName = 'vxlan0',
[Parameter(Position = 1)]
[int] $TimeoutSeconds = 60
)
$StartTime = Get-Date
while ($True) {
[TimeSpan] $ElapsedTime = $(Get-Date) - $StartTime
if ($ElapsedTime.TotalSeconds -ge $TimeoutSeconds) {
throw "Failed to create the network '$NetworkName' in $TimeoutSeconds seconds"
}
if ((Get-HnsNetwork | Where-Object { $_.Name -eq $NetworkName.ToLower() })) { break }
Write-Host "Waiting for the network '$NetworkName' to be created by flanneld..."
Start-Sleep 5
}
}
function Add-Configuration {
Param (
[Parameter(Position = 0, Mandatory)]
[string] $Name,
[Parameter(Position = 1, Mandatory)]
[object] $Value,
[Parameter(Mandatory, ValueFromPipeline)]
$InputObject,
[Management.Automation.PSMemberTypes] $MemberType = [Management.Automation.PSMemberTypes]::NoteProperty,
[switch] $PassThru,
[switch] $Force
)
Process {
$ConfigSection | Add-Member -MemberType $MemberType -Name $Name -Value $Value -PassThru:$PassThru -Force:$Force
}
}
function ConvertTo-IPAddress {
Param (
[Parameter(Position = 0, Mandatory, ValueFromPipeline)]
[UInt32[]] $Address
)
Process {
foreach ($a in $Address) {
$(foreach ($i in 0..3) {
$Divisor = [Math]::Pow(256, 3 - $i)
$Remainder = $a % $Divisor
($a - $Remainder) / $Divisor
$a = $Remainder
}) -join '.'
}
}
}
function ConvertTo-IntegerIPAddress {
Param (
[Parameter(Position = 0, Mandatory, ValueFromPipeline)]
[Net.IPAddress[]] $IPAddress
)
Process {
foreach ($addr in $IPAddress) {
$i = 3;
$addr.GetAddressBytes() | ForEach-Object -Begin {
[Uint32] $IntegerIP = 0;
$i = 3
} -Process {
$IntegerIP += $_ * [Math]::Pow(256, $i--)
} -End {
$IntegerIP
}
}
}
}
<#
.SYNOPSIS
Copies your SSH key to another machine and adds it to the Autherized SSK Keys file
(typically ~/.ssh/authorized_keys).
.PARAMETER PublicSshIdentityFile
The path and filename of the public SSH key to copy.
.PARAMETER RemoteUsername
The username with which to connect to the remote machine and to which to add the
public SSH key as an authorized key.
.PARAMETER RemoteHostname
The name of the remote host to connect to.
.PARAMETER Port
The port number that should be used when connecting to the remote host over SSH. The default is 22.
#>
function Copy-SshKey {
Param (
[Parameter(Position = 0, Mandatory)]
[Alias('i')]
[string] $PublicSshIdentityFile,
[Parameter(Position = 1, Mandatory)]
[string] $RemoteUsername,
[Parameter(Position = 2, Mandatory)]
[string] $RemoteHostname,
[Parameter(Position = 3)]
[int] $Port
)
Process {
$AddAuthorizedKeyCommand = "PUB_KEY=\`"$(Get-Content $PublicSshIdentityFile)\`" ; grep -q -F \`"`$PUB_KEY\`" ~/.ssh/authorized_keys 2>/dev/null || echo \`"`$PUB_KEY\`" >> ~/.ssh/authorized_keys"
ssh -T "${RemoteUsername}@${RemoteHostname}$(if ($Port) { ":$Port" })" $AddAuthorizedKeyCommand
}
}
function Get-ApiServerEndpoint {
(ConvertFrom-JSON $(kubectl.exe get endpoints --all-namespaces -o json | Out-String)).Items | Where-Object {
$_.Metadata.Name -eq 'kubernetes'
} | ForEach-Object {
"$($_.subsets[0].addresses[0].ip):$($_.subsets[0].ports[0].port)"
}
}
function Get-DockerImage {
Param (
[Parameter(Position = 0, ValueFromPipeline)]
[string[]] $Image
)
Process {
foreach ($i in $Image) {
if (!(docker images $i -q)) {
docker image pull $i
if (!(docker images $i -q)) {
throw "Failed to pull '$i'"
}
if ($i -imatch 'nanoserver|servercore') {
docker tag $i $($i -ireplace '(nanoserver|servercore):.*','$1:latest')
} elseif ($i -imatch 'pause') {
docker tag $i 'kubeletwin/pause'
}
}
}
}
}
function Get-GolangVersionMetadata {
[CmdletBinding()]
[OutputType('GoLang.VersionMetadata')]
Param (
[Parameter(ValueFromPipelineByPropertyName)]
[ValidatePattern('(?i)\d+\.\d+\.\d+|latest')]
[string[]] $Version = 'latest',
[Parameter(ValueFromPipelineByPropertyName)]
[ValidateSet('amd64','arm32v7','arm64v8','i386','ppc64le','s390x','src','windows-amd64')]
[string[]] $Architecture = 'windows-amd64'
)
Begin {
$GoLangVersionInfo = Invoke-RestMethod -Method GET -Uri 'https://raw.githubusercontent.com/docker-library/golang/master/versions.json' -ErrorAction Stop
}
Process {
foreach ($v in $Version) {
$GoLangVersionKey = $(
if ($v -ne 'latest') {
$MajorMinorVersion = $v -replace '^(\d+\.\d+).*$','$1'
$GoLangVersionInfo.PSObject.Properties |
Select-Object -ExpandProperty Name |
Where-Object { $_ -eq $MajorMinorVersion } |
Select-Object -First 1
} else {
$GoLangVersionInfo.PSObject.Properties |
Select-Object -Last 1 -ExpandProperty Name
}
)
$GoLangVersionMetadata = $GoLangVersionInfo.$GoLangVersionKey
foreach ($a in $Architecture) {
$a = $a.ToLower();
$GoLangArchVersionInfo = $GoLangVersionMetadata.arches.$a
[PSCustomObject]@{
PSTypeName = 'GoLang.VersionMetadata'
Version = $GoLangVersionMetadata.version
Arch = $GoLangArchVersionInfo.arch
Sha256 = $GoLangArchVersionInfo.sha256
Url = $GoLangArchVersionInfo.url
}
}
}
}
}
function Get-HnsScriptModule {
Param (
[string] $Path = $Script:KubernetesClusterNodeInstallationPath,
[switch] $Force
)
Process {
Write-Host "Downloading Windows HNS helper scripts..."
$Destination = Join-Path $Path 'hns.psm1'
DownloadFile -Url "https://github.com/Microsoft/SDN/raw/master/Kubernetes/windows/hns.psm1" -Destination $Destination -Force:$Force
}
}
function Get-InterfaceDefaultGateway {
Param (
[Parameter(Position = 0, ValueFromPipeline)]
[string[]] $InterfaceName = 'Ethernet'
)
Process {
foreach ($n in $InterfaceName) {
(Get-NetAdapter -InterfaceAlias $InterfaceName | Get-NetRoute -DestinationPrefix '0.0.0.0/0').NextHop
}
}
}
function Get-InterfaceIPAddress {
Param (
[Parameter(Position = 0, ValueFromPipeline)]
[string[]] $InterfaceName = 'Ethernet'
)
Process {
foreach ($n in $InterfaceName) {
Get-NetIpAddress -AddressFamily IPv4 -InterfaceAlias $n | Select-Object -ExpandProperty IPAddress
}
}
}
function Get-InterfaceSubnet {
Param (
[Parameter(Position = 0, ValueFromPipeline)]
[string[]] $InterfaceName = 'Ethernet'
)
Process {
foreach ($n in $InterfaceName) {
$NetAdapter = Get-NetAdapter -InterfaceAlias $n -ErrorAction Stop
$IpAddress = Get-NetIpAddress -AddressFamily IPv4 -InterfaceIndex $NetAdapter.InterfaceIndex | Select-Object -ExpandProperty IPAddress
$SubnetMask = (Get-CimInstance -ClassName 'WIN32_NETWORKADAPTERCONFIGURATION' | Where-Object { $_.InterfaceIndex -eq $NetAdapter.InterfaceIndex }).IPSubnet[0]
"$(ConvertTo-IPAddress ((ConvertTo-IntegerIPAddress $IpAddress) -band (ConvertTo-IntegerIPAddress $SubnetMask)))/$(Get-SubnetMaskLength $SubnetMask)"
}
}
}
function Get-KubernetesBinaries {
Param (
[Parameter(Position = 0)]
[string] $DestinationPath = $Script:KubernetesClusterNodeInstallationPath,
[Parameter(Position = 1)]
[string] $Version = '1.19.3',
[switch] $Force
)
Process {
$Version = $Version.ToLower().TrimStart('v');
try {
if ((Test-Path (Join-Path $DestinationPath kubelet.exe)) -and $Force -or $Force.IsPresent) {
Remove-Item -Path $DestinationPath\kube*.exe -Force
}
if (!(Test-Path (Join-Path $DestinationPath kubelet.exe))) {
Write-Host "Downloading Kubernetes v$Version..."
DownloadAndExpandTarGzArchive -Url "https://dl.k8s.io/v$Version/kubernetes-node-windows-amd64.tar.gz" -DestinationPath $Pwd
Write-Host "Finished downloading Kubernetes v$Version"
Move-Item $Pwd\kubernetes\node\bin\*.exe $DestinationPath
if ($env:PATH -inotmatch [Regex]::Escape($DestinationPath)) {
$env:PATH = "${env:PATH};$DestinationPath" -replace ';;',';'
[Environment]::SetEnvironmentVariable("PATH", $env:PATH, [EnvironmentVariableTarget]::Machine)
Write-Host "Added Kubernetes executables to the PATH"
}
}
} catch {
Write-Host 'Failed to download kuberenetes!'
throw
}
}
}
function Get-KubernetesClusterConfiguration {
Param (
[Parameter(Position = 0, Mandatory)]
[string] $MasterAddress,
[Parameter(Position = 1, Mandatory)]
[string] $MasterUsername
)
Process {
$KubernetesClusterConfigurationPath = Join-Path $Script:KubernetesClusterNodeInstallationPath 'config'
scp -o StrictHostKeyChecking=no "$($MasterUsername)@$($MasterAddress):~/.kube/config" $KubernetesClusterConfigurationPath
if (!$?) {
Write-Error "Failed to download kubernetes cluster configuration!"
} else {
Write-Host "Retrieved Kubernetes cluster configuration from '$MasterAddress'..."
}
Write-Host "Setting KUBECONFIG environment variable..."
$env:KUBECONFIG = $KubernetesClusterConfigurationPath
[Environment]::SetEnvironmentVariable("KUBECONFIG", $env:KUBECONFIG, [EnvironmentVariableTarget]::Machine)
}
}
function Get-KubernetesWindowsNodeConfiguration {
[OutputType('KubernetesWindowsNodeConfiguration')]
Param(
[Parameter(Position = 0)]
[string] $Path = $Script:KubernetesClusterNodeConfigurationPath
)
$NodeConfig = $null
if (Test-Path $Path) {
$NodeConfig = Get-Content $Path -Encoding UTF8 -Raw | ConvertFrom-JSON
if ('KubernetesWindowsNodeConfiguration' -notin $NodeConfig.PSObject.TypeNames) {
$null = $NodeConfig.PSObject.TypeNames.Add('KubernetesWindowsNodeConfiguration')
}
}
$NodeConfig
}
function Get-SubnetMaskLength {
Param (
[Parameter(Position = 0, Mandatory, ValueFromPipeline)]
[Net.IPAddress[]] $SubnetMask
)
Process {
foreach ($mask in $SubnetMask) {
("$($mask.GetAddressBytes() | ForEach-Object {
[Convert]::ToString($_, 2) # Converts $_ no binary representation
})" -replace '[\s0]').Length
}
}
}
function Get-WindowsBuildVersion {
[Cmdletbinding()]
[OutputType([string])]
Param()
(& cmd /c ver)[1] -replace '.*\[Version (.*)\]','$1'
}
function Install-ContainerRuntimeInterface {
[CmdletBinding()]
Param (
[ValidateSet('dockerd','containerd')]
[string] $Name = 'dockerd',
[switch] $Force
)
switch ($Name) {
'dockerd' { Install-Dockerd -Force:$Force }
'containerd' {
throw "The ContainerD CRI is not supported at this time."
#Install-ContainerD -Force:$Force
break
}
}
}
function Install-ContainersFeature {
[OutputType([Boolean])]
Param ( [switch] $Force )
if (!(Get-WindowsFeature -Name 'containers').Installed) {
if (!($Force -and $Force.IsPresent)) {
Write-Host "The Containers feature is not installed on this machine. It is required to configure this server as a Kubernetes node."
Write-Host "Installing Windows Defender will require this machine to be restarted before the Kubernetes node can be configured."
$resp = Read-HostEx -Prompt "Install the Containers feature? [Y/n] (Default 'Y') " -ExpectedValue 'Y','n'
}
if (($Force -and $Force.IsPresent) -or !$resp -or $resp -ieq 'y') {
Install-WindowsFeature -Name 'Containers'
Write-Host "The Containers feature has been uninstalled from this machine."
$True
}
} else {
$False
}
}
function Install-Dockerd {
Param( [switch] $Force )
if (!(Get-Package -Name docker -ProviderName DockerMsftProvider)) {
if (!($Force -and $Force.IsPresent)) {
Write-Host "Docker wes not found on this machine."
$Resp = Read-HostEx "Install Docker and necessary prerequisites on this machine? [Y/n] (Default 'Y') " -ExpectedValue 'Y', 'n'
}
if (($Force -and $Force.IsPresent) -or !$rsep -or $resp -ieq 'y') {
Write-Host "Installing Docker and any necessary prerequisites..."
if (!(Get-PackageProvider -Name NuGet)) {
Write-Host " The NuGet package provider was not found on this machine. Installing ..."
Install-PackageProvider -Name NuGet -Force -ErrorAction Stop
Write-Host " The NuGet package provider has been installed on this machine."
} else {
Write-Host " The NuGet package provider is already installed."
}
if (!(Get-Module -Name DockerMsftProvider)) {
Write-Host " The 'DockerMsftProvider' PowerShell module was not found on this machine. Installing ..."
Install-Module -Name DockerMsftProvider -Repository PSGallery -Force
Write-Host " The DockerMsftProvider PowerShell module has been installed on this machine."
} else {
Write-Host " The DockerMsftProvider PowerShell module is already installed."
Write-Host " Checking for DockerMsftProvider PowerShell module updates..."
Update-Module -Name DockerMsftProvider -Force
Write-Host " Updated the DockerMsftProvider PowerShell module to the latest version."
}
Write-Host " Installing Docker..."
Install-Package -Name docker -ProviderName DockerMsftProvider -Force