forked from schtritoff/hyperv-vm-provisioning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNew-HyperVCloudImageVM.ps1
1400 lines (1274 loc) · 63.4 KB
/
New-HyperVCloudImageVM.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
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
<#
.SYNOPSIS
Provision Cloud images on Hyper-V
.EXAMPLE
PS C:\> .\New-HyperVCloudImageVM.ps1 -VMProcessorCount 2 -VMMemoryStartupBytes 2GB -VHDSizeBytes 60GB -VMName "azure-1" -ImageVersion "jammy-azure" -VMGeneration 2
PS C:\> .\New-HyperVCloudImageVM.ps1 -VMProcessorCount 2 -VMMemoryStartupBytes 2GB -VHDSizeBytes 8GB -VMName "azure-2" -ImageVersion "13-azure" -VirtualSwitchName "SWBRIDGE" -VMGeneration 2 -VMMachine_StoragePath "D:\HyperV" -NetAddress 192.168.2.22/24 -NetGateway 192.168.2.1 -NameServers "192.168.2.1" -ShowSerialConsoleWindow -ShowVmConnectWindow
It should download cloud image and create VM, please be patient for first boot - it could take 10 minutes
and requires network connection on VM
.NOTES
Original script: https://blogs.msdn.microsoft.com/virtual_pc_guy/2015/06/23/building-a-daily-ubuntu-image-for-hyper-v/
References:
- https://git.launchpad.net/cloud-init/tree/cloudinit/sources/DataSourceAzure.py
- https://github.com/Azure/azure-linux-extensions/blob/master/script/ovf-env.xml
- https://cloudinit.readthedocs.io/en/latest/topics/datasources/azure.html
- https://github.com/fdcastel/Hyper-V-Automation
- https://bugs.launchpad.net/ubuntu/+source/walinuxagent/+bug/1700769
- https://gist.github.com/Informatic/0b6b24374b54d09c77b9d25595cdbd47
- https://www.neowin.net/news/canonical--microsoft-make-azure-tailored-linux-kernel/
- https://www.altaro.com/hyper-v/powershell-script-change-advanced-settings-hyper-v-virtual-machines/
Recommended: choco install putty -y
#>
#requires -Modules Hyper-V
#requires -RunAsAdministrator
[CmdletBinding()]
param(
[string] $VMName = "CloudVm",
[int] $VMGeneration = 2,
[int] $VMProcessorCount = 2,
[bool] $VMDynamicMemoryEnabled = $false,
[uint64] $VMMemoryStartupBytes = 1024MB,
[uint64] $VMMinimumBytes = $VMMemoryStartupBytes,
[uint64] $VMMaximumBytes = $VMMemoryStartupBytes,
[uint64] $VHDSizeBytes = 40GB,
[string] $VirtualSwitchName = $null,
[string] $VMVlanID = $null,
[string] $VMNativeVlanID = $null,
[string] $VMAllowedVlanIDList = $null,
[switch] $VMVMQ = $false,
[switch] $VMDhcpGuard = $false,
[switch] $VMRouterGuard = $false,
[switch] $VMPassthru = $false,
#[switch] $VMMinimumBandwidthAbsolute = $null,
#[switch] $VMMinimumBandwidthWeight = $null,
#[switch] $VMMaximumBandwidth = $null,
[switch] $VMMacAddressSpoofing = $false,
[switch] $VMExposeVirtualizationExtensions = $false,
[string] $VMVersion = $null, # version 8.0 for hyper-v 2016 compatibility, check all possible values with Get-VMHostSupportedVersion, see also: https://learn.microsoft.com/en-us/windows-server/virtualization/hyper-v/deploy/upgrade-virtual-machine-version-in-hyper-v-on-windows-or-windows-server#what-happens-if-i-dont-upgrade-the-virtual-machine-configuration-version
[string] $VMHostname = $VMName,
[string] $VMMachine_StoragePath = $null, # if defined setup machine path with storage path as subfolder
[string] $VMMachinePath = $null, # if not defined here default Virtal Machine path is used
[string] $VMStoragePath = $null, # if not defined here Hyper-V settings path / fallback path is set below
[bool] $ConvertImageToNoCloud = $false, # could be used for other image types that do not support NoCloud, not just Azure
[bool] $ImageTypeAzure = $false,
[string] $DomainName = "domain.local",
[string] $VMStaticMacAddress = $null,
[string] $NetInterface = "eth0",
[string] $NetAddress = $null,
[string] $NetNetmask = $null,
[string] $NetNetwork = $null,
[string] $NetGateway = $null,
[string] $NameServers = "1.1.1.1,1.0.0.1",
[string] $NetConfigType = $null, # ENI, v1, v2, ENI-file, dhclient
[string] $KeyboardLayout = "us", # 2-letter country code, for more info https://wiki.archlinux.org/title/Xorg/Keyboard_configuration
[string] $KeyboardModel, # default: "pc105"
[string] $KeyboardOptions, # example: "compose:rwin"
[string] $Locale = "en_US", # "en_US.UTF-8",
[string] $TimeZone = "UTC", # UTC or continental zones of IANA DB like: Europe/Berlin
[string] $CloudInitPowerState = "reboot", # poweroff, halt, or reboot , https://cloudinit.readthedocs.io/en/latest/reference/modules.html#power-state-change
[string] $CustomUserDataYamlFile,
[string] $GuestAdminUsername = "admin",
[string] $LOGO = "",
[string] $GuestAdminPassword = "Passw0rd",
[string] $GuestAdminSshPubKey,
[string] $GuestAdminSshPubKeyFile,
[string] $ImageVersion = "22.04", # $ImageName ="focal" # 20.04 LTS , $ImageName="bionic" # 18.04 LTS
[string] $ImageRelease = "release", # default option is get latest but could be fixed to some specific version for example "release-20210413"
[string] $ImageBaseUrl = "https://mirror.nju.edu.cn/ubuntu-cloud-images/releases", # alternative https://mirror.scaleuptech.com/ubuntu-cloud-images/releases
[bool] $BaseImageCheckForUpdate = $true, # check for newer image at Distro cloud-images site
[bool] $BaseImageCleanup = $true, # delete old vhd image. Set to false if using (TODO) differencing VHD
[switch] $ShowSerialConsoleWindow = $false,
[switch] $ShowVmConnectWindow = $false,
[switch] $Force = $false
)
[System.Threading.Thread]::CurrentThread.CurrentUICulture = "en-US"
[System.Threading.Thread]::CurrentThread.CurrentCulture = "en-US"
$NetAutoconfig = (($null -eq $NetAddress) -or ($NetAddress -eq "")) -and
(($null -eq $NetNetmask) -or ($NetNetmask -eq "")) -and
(($null -eq $NetNetwork) -or ($NetNetwork -eq "")) -and
(($null -eq $NetGateway) -or ($NetGateway -eq "")) -and
(($null -eq $VMStaticMacAddress) -or ($VMStaticMacAddress -eq ""))
if ($NetAutoconfig -eq $false) {
Write-Verbose "Given Network configuration - no checks done in script:"
Write-Verbose "VMStaticMacAddress: '$VMStaticMacAddress'"
Write-Verbose "NetInterface: '$NetInterface'"
Write-Verbose "NetAddress: '$NetAddress'"
Write-Verbose "NetNetmask: '$NetNetmask'"
Write-Verbose "NetNetwork: '$NetNetwork'"
Write-Verbose "NetGateway: '$NetGateway'"
Write-Verbose ""
}
# default error action
$ErrorActionPreference = 'Stop'
# pwsh (powershell core): try to load module hyper-v
if ($psversiontable.psversion.Major -ge 6) {
Import-Module hyper-v -SkipEditionCheck
}
# pwsh 7:
# - Provide a shim for Set-Content -Encoding Byte
# - Enable Progress bar (disable for older versions)
# The -Encoding value Byte has been removed from the filesystem provider
# cmdlets in pwsh 7. A new parameter, -AsByteStream, is now used to specify that a
# byte stream is required as input or that the output is a stream of bytes.
if ($PSVersionTable.PSVersion.Major -ge 7) {
function Set-ContentAsByteStream () { Set-Content @args -AsByteStream }
} else {
function Set-ContentAsByteStream () { Set-Content @args -Encoding Byte }
# Disable progress indicator because it is causing Invoke-WebRequest to be very
# slow in Windows Powershell
$ProgressPreference = "SilentlyContinue"
}
# check if verbose is present, src: https://stackoverflow.com/a/25491281/1155121
$verbose = $VerbosePreference -ne 'SilentlyContinue'
$ImageSupportsSecureBoot = $true
# check if running hyper-v host version 8.0 or later
# Get-VMHostSupportedVersion https://docs.microsoft.com/en-us/powershell/module/hyper-v/get-vmhostsupportedversion?view=win10-ps
# or use vmms version: $vmms = Get-Command vmms.exe , $vmms.version. src: https://social.technet.microsoft.com/Forums/en-US/dce2a4ec-10de-4eba-a19d-ae5213a2382d/how-to-tell-version-of-hyperv-installed?forum=winserverhyperv
$vmms = Get-Command vmms.exe
if (([System.Version]$vmms.fileversioninfo.productversion).Major -lt 10) {
throw "Unsupported Hyper-V version. Minimum supported version for is Hyper-V 2016."
}
# Helper function for no error file cleanup
function cleanupFile ([string]$file) {
if (test-path $file) {
Remove-Item $file -force
}
}
# Helper function for set file attribute to not compressed
function insureFileNotCompressed([string]$file) {
if (Test-Path $file) {
$fileAttributes = Get-Item $file | Select-Object -ExpandProperty Attributes
if ($fileAttributes -band [System.IO.FileAttributes]::Compressed) {
Write-Verbose "File is compressed: $file"
Write-Verbose "Removing compression attribute from file: $file"
compact.exe /u "$file"
}
}
else {
Write-Output "File does not exist: $file"
}
}
# set system wide place to put all data created by the script
# $dataPath = "$env:ProgramData\hyperv-vm-provisioning"
$dataPath = Join-Path $PSScriptRoot "data"
if (!(test-path $dataPath)) { mkdir -Path $dataPath | out-null }
# "$env:ProgramData\hyperv-vm-provisioning"
$cachePath = "$dataPath\cache"
if (!(test-path $cachePath)) {mkdir -Path $cachePath | out-null}
Write-Verbose "Using cache path: $cachePath"
$FQDN = $VMHostname.ToLower() + "." + $DomainName.ToLower()
# Instead of GUID, use 26 digit machine id suitable for BIOS serial number
# src: https://stackoverflow.com/a/67077483/1155121
# $vmMachineId = [Guid]::NewGuid().ToString()
$VmMachineId = "{0:####-####-####-####}-{1:####-####-##}" -f (Get-Random -Minimum 1000000000000000 -Maximum 9999999999999999),(Get-Random -Minimum 1000000000 -Maximum 9999999999)
$tempPath = [System.IO.Path]::GetTempPath() + "hv-" + $vmMachineId
mkdir -Path $tempPath | out-null
Write-Verbose "Using temp path: $tempPath"
# Download qemu-img from here: http://www.cloudbase.it/qemu-img-windows/
$qemuImgPath = Join-Path $PSScriptRoot "tools\qemu-img-4.1.0\qemu-img.exe"
# Windows version of tar for extracting tar.gz files, src: https://github.com/libarchive/libarchive
$bsdtarPath = Join-Path $PSScriptRoot "tools\bsdtar-3.7.6\bsdtar.exe"
# Update this to the release of Image that you want
# But Azure images can't be used because the waagent is trying to find ephemeral disk
# and it's searching causing 20 / 40 minutes minutes delay for 1st boot
# https://docs.microsoft.com/en-us/troubleshoot/azure/virtual-machines/cloud-init-deployment-delay
# and also somehow causing at sshd restart in password setting task to stuck for 30 minutes.
Switch ($ImageVersion) {
{ "18.04", "bionic" -eq $_ } {
$ImageOS = "ubuntu"
$ImageVersionName = "bionic"
$ImageVersion = "18.04"
$ImageRelease = "release" # default option is get latest but could be fixed to some specific version for example "release-20210413"
$ImageBaseUrl = "https://mirror.nju.edu.cn/ubuntu-cloud-images/releases" # alternative https://mirror.scaleuptech.com/ubuntu-cloud-images/releases
$ImageUrlRoot = "$ImageBaseUrl/$ImageVersionName/$ImageRelease/" # latest
$ImageFileName = "$ImageOS-$ImageVersion-server-cloudimg-amd64"
$ImageFileExtension = "img"
# Manifest file is used for version check based on last modified HTTP header
$ImageHashFileName = "SHA256SUMS"
$ImageManifestUrl = "$($ImageUrlRoot)$($ImageFileName).manifest"
break
}
{ "20.04", "focal" -eq $_ } {
$ImageOS = "ubuntu"
$ImageVersionName = "focal"
$ImageVersion = "20.04"
$ImageRelease = "release" # default option is get latest but could be fixed to some specific version for example "release-20210413"
$ImageBaseUrl = "https://mirror.nju.edu.cn/ubuntu-cloud-images/releases" # alternative https://mirror.scaleuptech.com/ubuntu-cloud-images/releases
$ImageUrlRoot = "$ImageBaseUrl/$ImageVersionName/$ImageRelease/" # latest
$ImageFileName = "$ImageOS-$ImageVersion-server-cloudimg-amd64"
$ImageFileExtension = "img"
# Manifest file is used for version check based on last modified HTTP header
$ImageHashFileName = "SHA256SUMS"
$ImageManifestUrl = "$($ImageUrlRoot)$($ImageFileName).manifest"
break
}
{ "22.04", "jammy" -eq $_ } {
$ImageOS = "ubuntu"
$ImageVersionName = "jammy"
$ImageVersion = "22.04"
$ImageRelease = "release" # default option is get latest but could be fixed to some specific version for example "release-20210413"
$ImageBaseUrl = "https://mirror.nju.edu.cn/ubuntu-cloud-images/releases" # alternative https://mirror.scaleuptech.com/ubuntu-cloud-images/releases
$ImageUrlRoot = "$ImageBaseUrl/$ImageVersionName/$ImageRelease/" # latest
$ImageFileName = "$ImageOS-$ImageVersion-server-cloudimg-amd64"
$ImageFileExtension = "img"
# Manifest file is used for version check based on last modified HTTP header
$ImageHashFileName = "SHA256SUMS"
$ImageManifestUrl = "$($ImageUrlRoot)$($ImageFileName).manifest"
break
}
{ "22.04-azure", "jammy-azure" -eq $_ } {
$ImageTypeAzure = $true
$ConvertImageToNoCloud = $true
$ImageOS = "ubuntu"
$ImageVersion = "22.04-azure"
#$ImageVersionName = "jammy"
$ImageRelease = "release" # default option is get latest but could be fixed to some specific version for example "release-20210413"
# https://cloud-images.ubuntu.com/releases/22.04/release/ubuntu-22.04-server-cloudimg-amd64-azure.vhd.tar.gz
$ImageBaseUrl = "https://mirror.nju.edu.cn/ubuntu-cloud-images/releases" # alternative https://mirror.scaleuptech.com/ubuntu-cloud-images/releases
$ImageUrlRoot = "$ImageBaseUrl/jammy/$ImageRelease/" # latest
$ImageFileName = "$ImageOS-22.04-server-cloudimg-amd64-azure" # should contain "vhd.*" version
$ImageFileExtension = "vhd.tar.gz" # or "vhd.zip" on older releases
# Manifest file is used for version check based on last modified HTTP header
$ImageHashFileName = "SHA256SUMS"
$ImageManifestUrl = "$($ImageUrlRoot)$($ImageFileName).vhd.manifest"
break
}
{ "24.04", "noble" -eq $_ } {
$ImageOS = "ubuntu"
$ImageVersionName = "noble"
$ImageVersion = "24.04"
$ImageRelease = "release" # default option is get latest but could be fixed to some specific version for example "release-20210413"
$ImageBaseUrl = "https://mirror.nju.edu.cn/ubuntu-cloud-images/releases" # alternative https://mirror.scaleuptech.com/ubuntu-cloud-images/releases
$ImageUrlRoot = "$ImageBaseUrl/$ImageVersionName/$ImageRelease/" # latest
$ImageFileName = "$ImageOS-$ImageVersion-server-cloudimg-amd64"
$ImageFileExtension = "img"
# Manifest file is used for version check based on last modified HTTP header
$ImageHashFileName = "SHA256SUMS"
$ImageManifestUrl = "$($ImageUrlRoot)$($ImageFileName).manifest"
break
}
{ "24.04-azure", "noble-azure" -eq $_ } {
$ImageTypeAzure = $true
$ConvertImageToNoCloud = $true
$ImageOS = "ubuntu"
$ImageVersion = "24.04-azure"
$ImageVersionName = "noble"
$ImageRelease = "release" # default option is get latest but could be fixed to some specific version for example "release-20210413"
# https://cloud-images.ubuntu.com/releases/22.04/release/ubuntu-22.04-server-cloudimg-amd64-azure.vhd.tar.gz
$ImageBaseUrl = "https://mirror.nju.edu.cn/ubuntu-cloud-images/releases" # alternative https://mirror.scaleuptech.com/ubuntu-cloud-images/releases
$ImageUrlRoot = "$ImageBaseUrl/noble/$ImageRelease/" # latest
$ImageFileName = "$ImageOS-24.04-server-cloudimg-amd64-azure" # should contain "vhd.*" version
$ImageFileExtension = "vhd.tar.gz" # or "vhd.zip" on older releases
# Manifest file is used for version check based on last modified HTTP header
$ImageHashFileName = "SHA256SUMS"
$ImageManifestUrl = "$($ImageUrlRoot)$($ImageFileName).vhd.manifest"
break
}
{ "10", "buster" -eq $_ } {
$ImageOS = "debian"
$ImageVersionName = "buster"
$ImageVersion = "10"
$ImageRelease = "latest" # default option is get latest but could be fixed to some specific version for example "release-20210413"
# http://cloud.debian.org/images/cloud/buster/latest/debian-10-azure-amd64.tar.xz
$ImageBaseUrl = "http://cloud.debian.org/images/cloud"
$ImageUrlRoot = "$ImageBaseUrl/$ImageVersionName/$ImageRelease/"
$ImageFileName = "$ImageOS-$ImageVersion-genericcloud-amd64" # should contain "vhd.*" version
$ImageFileExtension = "tar.xz" # or "vhd.tar.gz" on older releases
# Manifest file is used for version check based on last modified HTTP header
$ImageHashFileName = "SHA512SUMS"
$ImageManifestUrl = "$($ImageUrlRoot)$($ImageFileName).json"
$ImageSupportsSecureBoot = $false
break
}
{ "11", "bullseye" -eq $_ } {
$ImageOS = "debian"
$ImageVersionName = "bullseye"
$ImageVersion = "11"
$ImageRelease = "latest" # default option is get latest but could be fixed to some specific version for example "release-20210413"
# http://cloud.debian.org/images/cloud/bullseye/latest/debian-11-azure-amd64.tar.xz
$ImageBaseUrl = "http://cloud.debian.org/images/cloud"
$ImageUrlRoot = "$ImageBaseUrl/$ImageVersionName/$ImageRelease/"
$ImageFileName = "$ImageOS-$ImageVersion-genericcloud-amd64" # should contain "raw" version
$ImageFileExtension = "tar.xz" # or "vhd.tar.gz" on older releases
# Manifest file is used for version check based on last modified HTTP header
$ImageHashFileName = "SHA512SUMS"
$ImageManifestUrl = "$($ImageUrlRoot)$($ImageFileName).json"
break
}
{ "12", "bookworm" -eq $_ } {
$ImageOS = "debian"
$ImageVersionName = "bookworm"
$ImageVersion = "12"
$ImageRelease = "latest" # default option is get latest but could be fixed to some specific version for example "release-20210413"
# http://cloud.debian.org/images/cloud/bookworm/latest/debian-12-azure-amd64.tar.xz
$ImageBaseUrl = "http://cloud.debian.org/images/cloud"
$ImageUrlRoot = "$ImageBaseUrl/$ImageVersionName/$ImageRelease/"
$ImageFileName = "$ImageOS-$ImageVersion-genericcloud-amd64" # should contain "raw" version
$ImageFileExtension = "tar.xz" # or "vhd.tar.gz" on older releases
# Manifest file is used for version check based on last modified HTTP header
$ImageHashFileName = "SHA512SUMS"
$ImageManifestUrl = "$($ImageUrlRoot)$($ImageFileName).json"
break
}
{ "13-azure", "trixie-azure" -eq $_ } {
$ImageTypeAzure = $true
$ConvertImageToNoCloud = $true
$ImageOS = "debian"
$ImageVersionName = "trixie"
$ImageVersion = "13-azure"
$ImageRelease = "daily/latest" # default option is get latest but could be fixed to some specific version for example "release-20210413"
# http://cloud.debian.org/images/cloud/trixie/daily/latest/debian-trixie-azure-amd64-daily.tar.xz
$ImageBaseUrl = "http://cloud.debian.org/images/cloud"
$ImageUrlRoot = "$ImageBaseUrl/$ImageVersionName/$ImageRelease/"
#$ImageFileName = "$ImageOS-$ImageVersion-nocloud-amd64" # should contain "raw" version
$ImageFileName = "$ImageOS-13-azure-amd64-daily" # should contain "raw" version
$ImageFileExtension = "tar.xz"
# Manifest file is used for version check based on last modified HTTP header
$ImageHashFileName = "SHA512SUMS"
$ImageManifestUrl = "$($ImageUrlRoot)$($ImageFileName).json"
break
}
default {throw "Image version $_ is not supported."}
}
$ImagePath = "$($ImageUrlRoot)$($ImageFileName)"
$ImageHashPath = "$($ImageUrlRoot)$($ImageHashFileName)"
# use Azure specifics only if such cloud image is chosen
if ($ImageTypeAzure) {
Write-Verbose "Using Azure data source for cloud init in: $ImageFileName"
}
# Set path for storing all VM files
if (-not [string]::IsNullOrEmpty($VMMachine_StoragePath)) {
$VMMachinePath = $VMMachine_StoragePath.TrimEnd('\')
$VMStoragePath = "$VMMachine_StoragePath\$VMName\Virtual Hard Disks"
Write-Verbose "VMStoragePath set: $VMStoragePath"
}
# Get default Virtual Machine path (requires administrative privileges)
if ([string]::IsNullOrEmpty($VMMachinePath)) {
$VMMachinePath = (Get-VMHost).VirtualMachinePath
# fallback
if (-not $VMMachinePath) {
Write-Warning "Couldn't obtain VMMachinePath from Hyper-V settings via WMI"
$VMMachinePath = "C:\Users\Public\Documents\Hyper-V"
}
Write-Verbose "VMMachinePath set: $VMMachinePath"
}
if (!(test-path $VMMachinePath)) {New-Item -ItemType Directory -Path $VMMachinePath | out-null}
# Get default Virtual Hard Disk path (requires administrative privileges)
if ([string]::IsNullOrEmpty($VMStoragePath)) {
$VMStoragePath = (Get-VMHost).VirtualHardDiskPath
# fallback
if (-not $VMStoragePath) {
Write-Warning "Couldn't obtain VMStoragePath from Hyper-V settings via WMI"
$VMStoragePath = "C:\Users\Public\Documents\Hyper-V\Virtual Hard Disks"
}
Write-Verbose "VMStoragePath set: $VMStoragePath"
}
if (!(test-path $VMStoragePath)) {New-Item -ItemType Directory -Path $VMStoragePath | out-null}
# Delete the VM if it is around
$vm = Get-VM -VMName $VMName -ErrorAction 'SilentlyContinue'
if ($vm) {
& "${PSScriptRoot}\Cleanup-VM.ps1" $VMName -Force:$Force
}
# There is a documentation failure not mention needed dsmode setting:
# https://gist.github.com/Informatic/0b6b24374b54d09c77b9d25595cdbd47
# Only in special cloud environments its documented already:
# https://cloudinit.readthedocs.io/en/latest/topics/datasources/cloudsigma.html
# metadata for cloud-init
$metadata = @"
dsmode: local
instance-id: $($VmMachineId)
local-hostname: $($VMHostname)
"@
Write-Verbose "Metadata:"
Write-Verbose $metadata
Write-Verbose ""
# Azure: https://cloudinit.readthedocs.io/en/latest/topics/datasources/azure.html
# NoCloud: https://cloudinit.readthedocs.io/en/latest/topics/datasources/nocloud.html
# with static network examples included
if ($NetAutoconfig -eq $false) {
Write-Verbose "Network Autoconfiguration disabled."
#$NetConfigType = "v1"
#$NetConfigType = "v2"
#$NetConfigType = "ENI"
#$NetConfigType = "ENI-file" ## needed for Debian
#$NetConfigType = "dhclient"
if ([string]::IsNullOrEmpty($NetConfigType)) {
$NetConfigType = "v2"
Write-Verbose "Using default manual network configuration '$NetConfigType'."
} else {
Write-Verbose "NetworkConfigType: '$NetConfigType' assigned."
}
}
$networkconfig = $null
$network_write_files = $null
if ($NetAutoconfig -eq $false) {
Write-Verbose "Network autoconfig disabled; preparing networkconfig."
if ($NetConfigType -ieq "v1") {
Write-Verbose "v1 requested ..."
$networkconfig = @"
## /network-config on NoCloud cidata disk
## version 1 format
## version 2 is completely different, see the docs
## version 2 is not supported by Fedora
---
version: 1
config:
- enabled
- type: physical
name: $NetInterface
$(if (($null -eq $VMStaticMacAddress) -or ($VMStaticMacAddress -eq "")) { "#" })mac_address: $VMStaticMacAddress
$(if (($null -eq $NetAddress) -or ($NetAddress -eq "")) { "#" })subnets:
$(if (($null -eq $NetAddress) -or ($NetAddress -eq "")) { "#" }) - type: static
$(if (($null -eq $NetAddress) -or ($NetAddress -eq "")) { "#" }) address: $NetAddress
$(if (($null -eq $NetNetmask) -or ($NetNetmask -eq "")) { "#" }) netmask: $NetNetmask
$(if (($null -eq $NetNetwork) -or ($NetNetwork -eq "")) { "#" }) network: $NetNetwork
$(if (($null -eq $NetGateway) -or ($NetGateway -eq "")) { "#" }) routes:
$(if (($null -eq $NetGateway) -or ($NetGateway -eq "")) { "#" }) - network: 0.0.0.0
$(if (($null -eq $NetGateway) -or ($NetGateway -eq "")) { "#" }) netmask: 0.0.0.0
$(if (($null -eq $NetGateway) -or ($NetGateway -eq "")) { "#" }) gateway: $NetGateway
- type: nameserver
address: ['$($NameServers.Split(",") -join "', '" )']
search: ['$($DomainName)']
"@
} elseif ($NetConfigType -ieq "v2") {
Write-Verbose "v2 requested ..."
$networkconfig = @"
version: 2
ethernets:
$($NetInterface):
dhcp4: $NetAutoconfig
dhcp6: $NetAutoconfig
#$(if (($null -eq $VMStaticMacAddress) -or ($VMStaticMacAddress -eq "")) { "#" })mac_address: $VMStaticMacAddress
$(if (($null -eq $NetAddress) -or ($NetAddress -eq "")) { "#" })addresses:
$(if (($null -eq $NetAddress) -or ($NetAddress -eq "")) { "#" }) - $NetAddress
$(if (($null -eq $NetGateway) -or ($NetGateway -eq "")) { "#" })routes:
$(if (($null -eq $NetGateway) -or ($NetGateway -eq "")) { "#" }) - to: default
$(if (($null -eq $NetGateway) -or ($NetGateway -eq "")) { "#" }) via: $NetGateway
nameservers:
addresses: ['$($NameServers.Split(",") -join "', '" )']
search: ['$($DomainName)']
"@
} elseif ($NetConfigType -ieq "ENI") {
Write-Verbose "ENI requested ..."
$networkconfig = @"
# inline-ENI network configuration
network-interfaces: |
iface $NetInterface inet static
$(if (($null -ne $VMStaticMacAddress) -and ($VMStaticMacAddress -ne "")) { " hwaddress ether $VMStaticMacAddress`n"
})$(if (($null -ne $NetAddress) -and ($NetAddress -ne "")) { " address $NetAddress`n"
})$(if (($null -ne $NetNetwork) -and ($NetNetwork -ne "")) { " network $NetNetwork`n"
})$(if (($null -ne $NetNetmask) -and ($NetNetmask -ne "")) { " netmask $NetNetmask`n"
})$(if (($null -ne $NetBroadcast) -and ($NetBroadcast -ne "")) { " broadcast $Broadcast`n"
})$(if (($null -ne $NetGateway) -and ($NetGateway -ne "")) { " gateway $NetGateway`n"
})
dns-nameservers $($NameServers.Split(",") -join " ")
dns-search $DomainName
"@
} elseif ($NetConfigType -ieq "ENI-file") {
Write-Verbose "ENI-file requested ..."
# direct network configuration setup
$network_write_files = @"
# Static IP address
- content: |
# Configuration file for ENI networkmanager
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).
source /etc/network/interfaces.d/*
# The loopback network interface
auto lo
iface lo inet loopback
# The primary network interface
allow-hotplug eth0
iface $NetInterface inet static
$(if (($null -ne $NetAddress) -and ($NetAddress -ne "")) { " address $NetAddress`n"
})$(if (($null -ne $NetNetwork) -and ($NetNetwork -ne "")) { " network $NetNetwork`n"
})$(if (($null -ne $NetNetmask) -and ($NetNetmask -ne "")) { " netmask $NetNetmask`n"
})$(if (($null -ne $NetBroadcast) -and ($NetBroadcast -ne "")) { " broadcast $Broadcast`n"
})$(if (($null -ne $NetGateway) -and ($NetGateway -ne "")) { " gateway $NetGateway`n"
})$(if (($null -ne $VMStaticMacAddress) -and ($VMStaticMacAddress -ne "")) { " hwaddress ether $VMStaticMacAddress`n"
})
dns-nameservers $($NameServers.Split(",") -join " ")
dns-search $DomainName
path: /etc/network/interfaces.d/$($NetInterface)
"@
} elseif ($NetConfigType -ieq "dhclient") {
Write-Verbose "dhclient requested ..."
$network_write_files = @"
# Static IP address
- content: |
# Configuration file for /sbin/dhclient.
send host-name = gethostname();
lease {
interface `"$NetInterface`";
fixed-address $NetAddress;
option host-name `"$($FQDN)`";
option subnet-mask $NetAddress
#option broadcast-address 192.33.137.255;
option routers $NetGateway;
option domain-name-servers $($NameServers.Split(",") -join " ");
renew 2 2022/1/1 00:00:01;
rebind 2 2022/1/1 00:00:01;
expire 2 2022/1/1 00:00:01;
}
# Generate Stable Private IPv6 Addresses instead of hardware based ones
slaac private
path: /etc/dhcp/dhclient.conf
"@
} else {
Write-Warning "No network configuration version type defined for static IP address setup."
}
}
if ($null -ne $networkconfig) {
Write-Verbose ""
Write-Verbose "Network-Config:"
Write-Verbose $networkconfig
Write-Verbose ""
}
if ($null -ne $network_write_files) {
Write-Verbose ""
Write-Verbose "Network-Config for write_files:"
Write-Verbose $network_write_files
Write-Verbose ""
}
if ("" -eq $LOGO) {
$LOGO = $VMName.ToUpper()
}
# userdata for cloud-init, https://cloudinit.readthedocs.io/en/latest/topics/examples.html
$userdata = @"
#cloud-config
# vim: syntax=yaml
# created: $(Get-Date -UFormat "%b/%d/%Y %T %Z")
hostname: $($VMHostname)
fqdn: $($FQDN)
# cloud-init Bug 21.4.1: locale update prepends "LANG=" like in
# /etc/defaults/locale set and results into error
#locale: $Locale
timezone: $TimeZone
growpart:
mode: auto
devices: [/]
ignore_growroot_disabled: false
apt:
# http_proxy: http://host:port
# https_proxy: http://host:port
preserve_sources_list: false
# mirror in china
primary:
# arches is list of architectures the following config applies to
# the special keyword "default" applies to any architecture not explicitly
# listed.
- arches: [amd64, i386, default]
# uri is just defining the target as-is
uri: https://mirror.nju.edu.cn/$($ImageOS)
#
# via search one can define lists that are tried one by one.
# The first with a working DNS resolution (or if it is an IP) will be
# picked. That way one can keep one configuration for multiple
# subenvironments that select the working one.
search:
- https://mirrors.sustech.edu.cn/$($ImageOS)
- https://mirrors.tuna.tsinghua.edu.cn/$($ImageOS)
- https://mirror.nju.edu.cn/$($ImageOS)
# if no mirror is provided by uri or search but 'search_dns' is
# true, then search for dns names '<distro>-mirror' in each of
# - fqdn of this host per cloud metadata
# - localdomain
# - no domain (which would search domains listed in /etc/resolv.conf)
# If there is a dns entry for <distro>-mirror, then it is assumed that
# there is a distro mirror at http://<distro>-mirror.<domain>/<distro>
#
# That gives the cloud provider the opportunity to set mirrors of a distro
# up and expose them only by creating dns entries.
#
# if none of that is found, then the default distro mirror is used
search_dns: false
#
# If multiple of a category are given
# 1. uri
# 2. search
# 3. search_dns
# the first defining a valid mirror wins (in the order as defined here,
# not the order as listed in the config).
#
# Additionally, if the repository requires a custom signing key, it can be
# specified via the same fields as for custom sources:
# 'keyid': providing a key to import via shortid or fingerprint
# 'key': providing a raw PGP key
# 'keyserver': specify an alternate keyserver to pull keys from that
# were specified by keyid
security:
- uri: $(if ($ImageOS -eq "debian") {"https://security.debian.org/debian-security"} elseif ($ImageOS -eq "ubuntu") {"http://security.ubuntu.com/ubuntu"})
arches: [default]
package_update: true
package_upgrade: true
package_reboot_if_required: true
packages:
$(
# hyperv linux integration services https://poweradm.com/install-linux-integration-services-hyper-v/
if ($ImageOS -eq "debian") {
" - hyperv-daemons"}
elseif (($ImageOS -eq "ubuntu")) {
# azure kernel https://learn.microsoft.com/en-us/windows-server/virtualization/hyper-v/Supported-Ubuntu-virtual-machines-on-Hyper-V#notes
" - linux-tools-virtual
- linux-cloud-tools-virtual
- linux-azure"
})
- eject
- console-setup
- keyboard-configuration
# extra
- zsh
- git
- curl
- wget
- tmux
- htop
- screen
- figlet
- neovim
- net-tools
# desktop
- ubuntu-desktop
- gdm3
# documented keyboard option, but not implemented ?
# https://cloudinit.readthedocs.io/en/latest/topics/modules.html#keyboard
# https://github.com/sulmone/X11/blob/59029dc09211926a5c95ff1dd2b828574fefcde6/share/X11/xkb/rules/xorg.lst#L181
keyboard:
layout: $KeyboardLayout
$(if (-not [string]::IsNullOrEmpty($KeyboardModel)) {" model: $KeyboardModel"})
$(if (-not [string]::IsNullOrEmpty($KeyboardOptions)) {" options: $KeyboardOptions"})
# https://learn.microsoft.com/en-us/azure/virtual-machines/linux/cloudinit-add-user#add-a-user-to-a-vm-with-cloud-init
users:
- default
- name: $($GuestAdminUsername)
no_user_group: true
groups: [sudo]
shell: /bin/bash
sudo: ALL=(ALL) NOPASSWD:ALL
lock_passwd: false
plain_text_passwd: $($GuestAdminPassword)
$(if (-not [string]::IsNullOrEmpty($GuestAdminSshPubKey)) {
" ssh_authorized_keys:
- $GuestAdminSshPubKey
"})
$(if (-not [string]::IsNullOrEmpty($GuestAdminSshPubKeyFile)) {
" ssh_authorized_keys:
- $(Get-Content -Path $GuestAdminSshPubKeyFile -Raw)
"})
disable_root: true # true: notify default user account / false: allow root ssh login
ssh_pwauth: true # true: allow login with password; else only with setup pubkey(s)
#ssh_authorized_keys:
# - ssh-rsa AAAAB... comment
# bootcmd can be setup like runcmd but would run at very early stage
# on every cloud-init assisted boot if not prepended by command "cloud-init-per once|instance|always":
$(if ($NetAutoconfig -eq $true) { "#" })bootcmd:
$(if ($NetAutoconfig -eq $true) { "#" }) - [ cloud-init-per, once, fix-dhcp, sh, -c, "if test -f /etc/dhcp/dhclient.conf; then sed -e 's/#timeout 60;/timeout 1;/g' -i /etc/dhcp/dhclient.conf; fi" ]
runcmd:
$(if (($NetAutoconfig -eq $false) -and ($NetConfigType -ieq "ENI-file")) {
" # maybe condition OS based for Debian only and not ENI-file based?
# Comment out cloud-init based dhcp configuration for $NetInterface
- [ rm, /etc/network/interfaces.d/50-cloud-init ]
"}) # - [ sh, -c, echo "127.0.0.1 localhost" >> /etc/hosts ]
# force password change on 1st boot
# - [ chage, -d, 0, $($GuestAdminUsername) ]
# remove metadata iso
- [ sh, -c, "if test -b /dev/cdrom; then eject; fi" ]
- [ sh, -c, "if test -b /dev/sr0; then eject /dev/sr0; fi" ]
$(if ($ImageTypeAzure) { "
# dont start waagent service since it useful only for azure/scvmm
- [ systemctl, stop, walinuxagent.service]
- [ systemctl, disable, walinuxagent.service]
"}) # disable cloud init on next boot (https://cloudinit.readthedocs.io/en/latest/topics/boot.html, https://askubuntu.com/a/1047618)
- [ sh, -c, touch /etc/cloud/cloud-init.disabled ]
# set locale
# cloud-init Bug 21.4.1: locale update prepends "LANG=" like in
# /etc/defaults/locale set and results into error
- [ locale-gen, "$($Locale).UTF-8" ]
- [ update-locale, "$($Locale).UTF-8" ]
# documented keyboard option, but not implemented ?
# change keyboard layout, src: https://askubuntu.com/a/784816
- [ sh, -c, sed -i 's/XKBLAYOUT=\"\w*"/XKBLAYOUT=\"'$($KeyboardLayout)'\"/g' /etc/default/keyboard ]
- [ sh , -c , chsh -s /bin/zsh $($GuestAdminUsername) ]
- [ sh , -c , update-alternatives --set vim /usr/bin/nvim ]
# - runuser -l $($GuestAdminUsername) -c 'sh -c "`$(curl -fsSL https://raw.githubusercontent.com/coreycole/oh-my-zsh/master/tools/install.sh)"'
- git clone https://mirror.nju.edu.cn/git/ohmyzsh.git /home/$($GuestAdminUsername)/.oh-my-zsh
- cp /home/$($GuestAdminUsername)/.oh-my-zsh/templates/zshrc.zsh-template /home/$($GuestAdminUsername)/.zshrc
- chsh -s `$(which zsh) $($GuestAdminUsername)
- fgGreen='%{`$fg[green]%}'
- fgCyan='%{`$fg[cyan]%}'
- fgReset='%{`$reset_color%}'
- retStatus='`${ret_status}'
- gitInfo='`$(git_prompt_info)'
- runuser -l $($GuestAdminUsername) -c "echo export PROMPT=\''`${fgGreen}%n@%m`${fgReset} `${retStatus} `${fgCyan}%/`${fgReset} `${gitInfo}'\'" >> /home/$($GuestAdminUsername)/.zshrc
- echo "source ~/.profile" >> /home/$($GuestAdminUsername)/.zshrc
# docker ce
- export DOWNLOAD_URL="https://mirror.nju.edu.cn/docker-ce"
# original: https://get.docker.com/
- wget -O- https://cdn.jsdelivr.net/gh/docker/docker-install/install.sh | sh
- usermod -aG docker $($GuestAdminUsername)
- mkdir -p /home/$($GuestAdminUsername)/stacks
write_files:
- content: |
#!/bin/sh
figlet -f lean "$($LOGO)" | tr ' _/' ' ||'
path: /etc/update-motd.d/11-logo
permissions: "0755"
# hyperv-daemons package in mosts distros is missing this file and spamming syslog:
# https://github.com/torvalds/linux/blob/master/tools/hv/hv_get_dns_info.sh
- content: |
#!/bin/bash
# This example script parses /etc/resolv.conf to retrive DNS information.
# In the interest of keeping the KVP daemon code free of distro specific
# information; the kvp daemon code invokes this external script to gather
# DNS information.
# This script is expected to print the nameserver values to stdout.
# Each Distro is expected to implement this script in a distro specific
# fashion. For instance on Distros that ship with Network Manager enabled,
# this script can be based on the Network Manager APIs for retrieving DNS
# entries.
cat /etc/resolv.conf 2>/dev/null | awk '/^nameserver/ { print $2 }'
path: /usr/libexec/hypervkvpd/hv_get_dns_info
# hyperv-daemons package in mosts distros is missing this file and spamming syslog:
# https://github.com/torvalds/linux/blob/master/tools/hv/hv_get_dhcp_info.sh
- content: |
#!/bin/bash
# SPDX-License-Identifier: GPL-2.0
# This example script retrieves the DHCP state of a given interface.
# In the interest of keeping the KVP daemon code free of distro specific
# information; the kvp daemon code invokes this external script to gather
# DHCP setting for the specific interface.
#
# Input: Name of the interface
#
# Output: The script prints the string "Enabled" to stdout to indicate
# that DHCP is enabled on the interface. If DHCP is not enabled,
# the script prints the string "Disabled" to stdout.
#
# Each Distro is expected to implement this script in a distro specific
# fashion. For instance, on Distros that ship with Network Manager enabled,
# this script can be based on the Network Manager APIs for retrieving DHCP
# information.
# RedHat based systems
#if_file="/etc/sysconfig/network-scripts/ifcfg-"$1
# Debian based systems
if_file=`"/etc/network/interfaces.d/*`"
dhcp=`$(grep `"dhcp`" `$if_file 2>/dev/null)
if [ "$dhcp" != "" ];
then
echo "Enabled"
else
echo "Disabled"
fi
path: /usr/libexec/hypervkvpd/hv_get_dhcp_info
$(if ($null -ne $network_write_files) { $network_write_files
})
manage_etc_hosts: true
manage_resolv_conf: true
resolv_conf:
$(if ($NameServers.Contains("1.1.1.1")) { " # cloudflare dns, src: https://1.1.1.1/dns/" }
) nameservers: ['$( $NameServers.Split(",") -join "', '" )']
searchdomains:
- $($DomainName)
domain: $($DomainName)
power_state:
mode: $($CloudInitPowerState)
message: Provisioning finished, will $($CloudInitPowerState) ...
timeout: 15
"@
Write-Verbose "Userdata:"
Write-Verbose $userdata
Write-Verbose ""
# override default userdata with custom yaml file: $CustomUserDataYamlFile
# the will be parsed for any powershell variables, src: https://deadroot.info/scripts/2018/09/04/PowerShell-Templating
if (-not [string]::IsNullOrEmpty($CustomUserDataYamlFile) -and (Test-Path $CustomUserDataYamlFile)) {
Write-Verbose "Using custom userdata yaml $CustomUserDataYamlFile"
$userdata = $ExecutionContext.InvokeCommand.ExpandString( $(Get-Content $CustomUserDataYamlFile -Raw) ) # parse variables
}
if ($ImageTypeAzure) {
# cloud-init configuration that will be merged, see https://cloudinit.readthedocs.io/en/latest/topics/datasources/azure.html
$dscfg = @"
datasource:
Azure:
agent_command: ["/bin/systemctl", "disable walinuxagent.service"]
# agent_command: __builtin__
apply_network_config: false
# data_dir: /var/lib/waagent
# dhclient_lease_file: /var/lib/dhcp/dhclient.eth0.leases
# disk_aliases:
# ephemeral0: /dev/disk/cloud/azure_resource
# hostname_bounce:
# interface: eth0
# command: builtin
# policy: true
# hostname_command: hostname
set_hostname: false
"@
# src https://github.com/Azure/WALinuxAgent/blob/develop/tests/data/ovf-env.xml
# src2: https://github.com/canonical/cloud-init/blob/5e6ecc615318b48e2b14c2fd1f78571522848b4e/tests/unittests/sources/test_azure.py#L328
$ovfenvxml = [xml]@"
<?xml version="1.0" encoding="utf-8"?>
<ns0:Environment xmlns="http://schemas.dmtf.org/ovf/environment/1"
xmlns:ns0="http://schemas.dmtf.org/ovf/environment/1"
xmlns:ns1="http://schemas.microsoft.com/windowsazure"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ns1:ProvisioningSection>
<ns1:Version>1.0</ns1:Version>
<ns1:LinuxProvisioningConfigurationSet>
<ns1:ConfigurationSetType>LinuxProvisioningConfiguration</ns1:ConfigurationSetType>
<ns1:HostName>$($VMHostname)</ns1:HostName>
<ns1:UserName>$($GuestAdminUsername)</ns1:UserName>
<ns1:UserPassword>$($GuestAdminPassword)</ns1:UserPassword>
<ns1:DisableSshPasswordAuthentication>false</ns1:DisableSshPasswordAuthentication>
<ns1:CustomData>$([Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($userdata)))</ns1:CustomData>
<dscfg>$([Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($dscfg)))</dscfg>
<!-- TODO add ssh key provisioning support -->
<!--
<SSH>
<PublicKeys>
<PublicKey>
<Fingerprint>EB0C0AB4B2D5FC35F2F0658D19F44C8283E2DD62</Fingerprint>
<Path>$HOME/UserName/.ssh/authorized_keys</Path>
<Value>ssh-rsa AAAANOTAREALKEY== [email protected]</Value>
</PublicKey>
</PublicKeys>
<KeyPairs>
<KeyPair>
<Fingerprint>EB0C0AB4B2D5FC35F2F0658D19F44C8283E2DD62</Fingerprint>
<Path>$HOME/UserName/.ssh/id_rsa</Path>
</KeyPair>
</KeyPairs>
</SSH>
-->
</ns1:LinuxProvisioningConfigurationSet>
</ns1:ProvisioningSection>
<ns1:PlatformSettingsSection>
<ns1:Version>1.0</ns1:Version>
<ns1:PlatformSettings>
<ns1:KmsServerHostname>kms.core.windows.net</ns1:KmsServerHostname>
<ns1:ProvisionGuestAgent>false</ns1:ProvisionGuestAgent>
<ns1:GuestAgentPackageName xsi:nil="true" />
<ns1:PreprovisionedVm>true</ns1:PreprovisionedVm>
<ns1:PreprovisionedVMType>Unknown</ns1:PreprovisionedVMType> <!-- https://github.com/canonical/cloud-init/blob/5e6ecc615318b48e2b14c2fd1f78571522848b4e/cloudinit/sources/DataSourceAzure.py#L94 -->
</ns1:PlatformSettings>
</ns1:PlatformSettingsSection>
</ns0:Environment>
"@
}
# Make temp location for iso image
mkdir -Path "$($tempPath)\Bits" | out-null
# Output metadata, networkconfig and userdata to file on disk
Set-ContentAsByteStream "$($tempPath)\Bits\meta-data" ([byte[]][char[]] "$metadata")
if (($NetAutoconfig -eq $false) -and
(($NetConfigType -ieq "v1") -or ($NetConfigType -ieq "v2"))) {
Set-ContentAsByteStream "$($tempPath)\Bits\network-config" ([byte[]][char[]] "$networkconfig")
}
Set-ContentAsByteStream "$($tempPath)\Bits\user-data" ([byte[]][char[]] "$userdata")
if ($ImageTypeAzure) {
$ovfenvxml.Save("$($tempPath)\Bits\ovf-env.xml");
}
# Create meta data ISO image, src: https://cloudinit.readthedocs.io/en/latest/topics/datasources/nocloud.html
# both azure and nocloud support same cdrom filesystem https://github.com/canonical/cloud-init/blob/606a0a7c278d8c93170f0b5fb1ce149be3349435/cloudinit/sources/DataSourceAzure.py#L1972
Write-Host "Creating metadata iso for VM provisioning... " -NoNewline
$metaDataIso = "$($VMStoragePath)\$($VMName)-metadata.iso"
Write-Verbose "Filename: $metaDataIso"
cleanupFile $metaDataIso
& "$PSScriptRoot\New-ISOFile.ps1" -source "$tempPath\Bits" -title "CIDATA" -media "DISK" -destinationIso "$metaDataIso" 1> $null
if (!(test-path "$metaDataIso")) {throw "Error creating metadata iso"}
Write-Verbose "Metadata iso written"
Write-Host -ForegroundColor Green " Done."
# storage location for base images
$ImageCachePath = Join-Path $cachePath $("CloudImage-$ImageOS-$ImageVersion")
if (!(test-path $ImageCachePath)) {mkdir -Path $ImageCachePath | out-null}
# Get the timestamp of the target build on the cloud-images site
$BaseImageStampFile = join-path $ImageCachePath "baseimagetimestamp.txt"
[string]$stamp = ''
if (test-path $BaseImageStampFile) {
$stamp = (Get-Content -Path $BaseImageStampFile | Out-String).Trim()
Write-Verbose "Timestamp from cache: $stamp"
}
if ($BaseImageCheckForUpdate -or ($stamp -eq '')) {
$url = $ImageManifestUrl
try {
$lastModified = (Invoke-WebRequest -TimeoutSec 12 -UseBasicParsing "$url").Headers.'Last-Modified'
$stamp=[DateTime]::Parse($lastModified).ToUniversalTime().ToString("yyyyMMddHHmmss")
Set-Content -path $BaseImageStampFile -value $stamp -force
Write-Verbose "Timestamp from web (new): $stamp"
} catch
{
Write-Verbose "Could not reach server: $url. We assume same timestamp: $stamp"
}
}
# check if local cached cloud image is the target one per $stamp
if (!(test-path "$($ImageCachePath)\$($ImageOS)-$($stamp).$($ImageFileExtension)") `
-and !(test-path "$($ImageCachePath)\$($ImageOS)-$($stamp).vhd") # download only if VHD of requested $stamp version is not present in cache
) {
try {
# If we do not have a matching image - delete the old ones and download the new one
Write-Verbose "Did not find: $($ImageCachePath)\$($ImageOS)-$($stamp).$($ImageFileExtension)"
Write-Host 'Removing old images from cache...' -NoNewline
Remove-Item "$($ImageCachePath)" -Exclude 'baseimagetimestamp.txt',"$($ImageOS)-$($stamp).*" -Recurse -Force
Write-Host -ForegroundColor Green " Done."
# get headers for content length
Write-Host 'Check new image size ...' -NoNewline
$response = Invoke-WebRequest "$($ImagePath).$($ImageFileExtension)" -UseBasicParsing -Method Head -TimeoutSec 12
$contentLength = $response.Headers["Content-Length"]
# Note Content-Length can be a string[] in powershell 7
if ($contentLength -is [array]) {
$contentLength = $contentLength[0]
}
$downloadSize = [int] $contentLength
Write-Host -ForegroundColor Green " Done."
Write-Host "Downloading new Cloud image ($([int]($downloadSize / 1024 / 1024)) MB)..." -NoNewline
Write-Verbose $(Get-Date)
# download new image