forked from lucabol/DTLCustomImagesLab
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Az.DevTestLabs2.psm1
4239 lines (3646 loc) · 156 KB
/
Az.DevTestLabs2.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
#region COMMON FUNCTIONS
# We are using strict mode for added safety
Set-StrictMode -Version Latest
# We require a relatively new version of Powershell
#requires -Version 3.0
# To understand the code below read here: https://docs.microsoft.com/en-us/powershell/azure/migrate-from-azurerm-to-az?view=azps-2.1.0
# Having both the Az and AzureRm Module installed is not supported, but it is probably common. The library should work in such case, but warn.
# Checking for the presence of the Az module, brings it into memory which causes an exception if AzureRm is present installed in the system. So checking for absence of AzureRm instead.
# If both are absent, then the user will get an error later on when trying to access it.
# If you have the AzureRm module, then everything works fine
# If you have the Az module, we need to enable the AzureRmAliases
$azureRm = Get-InstalledModule -Name "AzureRM" -ErrorAction SilentlyContinue
$az = Get-Module -Name "Az.Accounts" -ListAvailable
$justAz = $az -and -not ($azureRm -and $azureRm.Version.Major -ge 6)
$justAzureRm = $azureRm -and (-not $az)
if($azureRm -and $az) {
Write-Warning "You have both Az and AzureRm module installed. That is not officially supported. For more read here: https://docs.microsoft.com/en-us/powershell/azure/migrate-from-azurerm-to-az"
}
if($justAzureRm) {
if ($azureRm.Version.Major -lt 6) {
Write-Error "This module does not work correctly with version 5 or lower of AzureRM, please upgrade to a newer version of Azure PowerShell in order to use this module."
} else {
# This is not defaulted in older versions of AzureRM
Enable-AzContextAutosave -Scope Process | Out-Null
Write-Warning "You are using the deprecated AzureRM module. For more info, read https://docs.microsoft.com/en-us/powershell/azure/migrate-from-azurerm-to-az"
}
}
if($justAz) {
Enable-AzureRmAlias -Scope Local
Enable-AzContextAutosave -Scope Process | Out-Null
}
# We want to track usage of library, so adding GUID to user-agent at loading and removig it at unloading
$libUserAgent = "pid-bd1d84d0-5ddb-4ab9-b951-393e656bb054"
[Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent($libUserAgent)
$MyInvocation.MyCommand.ScriptBlock.Module.OnRemove = {
[Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.RemoveUserAgent($libUserAgent)
}
# The reason for using the following function and managing errors as done in the cmdlets below is described
# at the link here: https://github.com/PoshCode/PowerShellPracticeAndStyle/issues/37#issuecomment-347257738
# The scheme permits writing the cmdlet code assuming the code after an error is not executed,
# and at the same time allows the caller to decide if the cmdlet *overall* should stop or continue for errors
# by using the standard ErrorAction syntax. It also mentions the correct cmdlet name in the text for the error
# without exposing the innards of the function. The price to pay is boilerplate code, reduced by BeginPreamble.
# You might think you might reduce boilerplate even more by creating a function that takes
# a scriptBlock and wrap it in the correct begig{} process {try{} catch{}} end {}
# but that ends up showing the source line of the error as such function, not the cmdlet.
# Import (with . syntax) this at the start of each begin block
function BeginPreamble {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseDeclaredVarsMoreThanAssignments", "", Scope="Function")]
param()
Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
$callerEA = $ErrorActionPreference
$ErrorActionPreference = 'Stop'
}
function PrintHashtable {
param($hash)
return ($hash.Keys | ForEach-Object { "$_ $($hash[$_])" }) -join "|"
}
# Getting labs that don't exist shouldn't fail, but return empty for composibility
# Also I am forced to do client side query because when you add -ExpandProperty to Get-AzureRmResource it disables wildcard?????
# Also I know that treating each case separately is ugly looking, but there are various bugs that might be fixed in Get-AzureRmResource
# at which point more queries can be moved server side, so leave it as it is for now.
function MyGetResourceLab {
param($Name, $ResourceGroupName)
$ResourceType = "Microsoft.DevTestLab/labs"
if($ResourceGroupName -and (-not $ResourceGroupName.Contains("*"))) { # Proper RG
if($Name -and (-not $Name.Contains("*"))) { # Proper RG, Proper Name
Get-AzureRmResource -ExpandProperties -resourcetype $ResourceType -ResourceGroupName $ResourceGroupName -ApiVersion "2018-10-15-preview" -Name $Name -EA SilentlyContinue
} else { #Proper RG, wild name
Get-AzureRmResource -ExpandProperties -resourcetype $ResourceType -ResourceGroupName $ResourceGroupName -ApiVersion "2018-10-15-preview" -EA SilentlyContinue | Where-Object { $_.ResourceId -like "*/labs/$Name"}
}
} else { # Wild RG forces client side query anyhow
Get-AzureRmResource -ExpandProperties -resourcetype $ResourceType -EA SilentlyContinue | Where-Object { $_.ResourceId -like "*/resourcegroups/$ResourceGroupName/*/labs/$Name"}
}
}
function MyGetResourceVm {
param($Name, $LabName, $ResourceGroupName)
$ResourceType = "Microsoft.DevTestLab/labs/virtualMachines"
if($ResourceGroupName -and (-not $ResourceGroupName.Contains("*"))) { # Proper RG
if($LabName -and (-not $LabName.Contains("*"))) { # Proper RG, Proper LabName
if($Name -and (-not $Name.Contains("*"))) { # Proper RG, Proper LabName, Proper Name
if($azureRm) {
Get-AzureRmResource -ExpandProperties -resourcetype $ResourceType -ResourceGroupName $ResourceGroupName -Name "$LabName/$Name" -EA SilentlyContinue
} else {
Get-AzureRmResource -ExpandProperties -resourcetype $ResourceType -ResourceGroupName $ResourceGroupName -EA SilentlyContinue | Where-Object { $_.ResourceId -like "*/labs/$LabName/virtualmachines/$Name"}
}
} else { # Proper RG, Proper LabName, Improper Name
Get-AzureRmResource -ExpandProperties -resourcetype $ResourceType -ResourceGroupName $ResourceGroupName -EA SilentlyContinue | Where-Object { $_.ResourceId -like "*/labs/$LabName/virtualmachines/$Name"}
}
} else { # Proper RG, Improper LabName
Get-AzureRmResource -ExpandProperties -resourcetype $ResourceType -ResourceGroupName $ResourceGroupName -EA SilentlyContinue | Where-Object { $_.ResourceId -like "*/labs/$LabName/virtualmachines/$Name"}
}
} else { # Improper RG forces client side query anyhow
Get-AzureRmResource -ExpandProperties -resourcetype $ResourceType -EA SilentlyContinue | Where-Object { $_.ResourceId -like "*/resourcegroups/$ResourceGroupName/*/labs/$LabName/virtualmachines/$Name"}
}
}
function Get-AzureRmCachedAccessToken()
{
$ErrorActionPreference = 'Stop'
Set-StrictMode -Off
if ($justAz) {
if (-not (Get-Module -Name Az.Resources)) {
Import-Module -Name Az.Resources
}
$azureRmProfileModuleVersion = (Get-Module Az.Resources).Version
} else {
if(-not (Get-Module -Name AzureRm.Profile)) {
Import-Module -Name AzureRm.Profile
}
$azureRmProfileModuleVersion = (Get-Module AzureRm.Profile).Version
}
# refactoring performed in AzureRm.Profile v3.0 or later
if($azureRmProfileModuleVersion.Major -ge 3 -or ($justAz -and $azureRmProfileModuleVersion.Major -ge 1)) {
$azureRmProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile
if(-not $azureRmProfile.Accounts.Count) {
Write-Error "Ensure you have logged in before calling this function."
}
} else {
# AzureRm.Profile < v3.0
$azureRmProfile = [Microsoft.WindowsAzure.Commands.Common.AzureRmProfileProvider]::Instance.Profile
if(-not $azureRmProfile.Context.Account.Count) {
Write-Error "Ensure you have logged in before calling this function."
}
}
$currentAzureContext = Get-AzureRmContext
$profileClient = New-Object Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient($azureRmProfile)
Write-Debug ("Getting access token for tenant" + $currentAzureContext.Subscription.TenantId)
$token = $profileClient.AcquireAccessToken($currentAzureContext.Subscription.TenantId)
$token.AccessToken
}
function GetHeaderWithAuthToken {
$authToken = Get-AzureRmCachedAccessToken
Write-Debug $authToken
$header = @{
'Content-Type' = 'application\json'
"Authorization" = "Bearer " + $authToken
}
return $header
}
function Get-AzDtlLab {
[CmdletBinding()]
param(
[parameter(Mandatory=$false,ValueFromPipelineByPropertyName = $true, ValueFromPipeline=$true, HelpMessage="Name of the lab(s) to retrieve. This parameter supports wildcards at the beginning and/or end of the string.")]
[ValidateNotNullOrEmpty()]
[string]
$Name = "*",
[parameter(Mandatory=$false, ValueFromPipelineByPropertyName = $true, HelpMessage="Name of the resource group to get the lab from. It must be an existing one.")]
[ValidateNotNullOrEmpty()]
[string] $ResourceGroupName = '*'
)
begin {. BeginPreamble}
process {
try {
Write-verbose "Retrieving lab $Name ..."
MyGetResourceLab -Name $Name -ResourceGroupName $ResourceGroupName
Write-verbose "Retrieved lab $Name."
} catch {
Write-Error -ErrorRecord $_ -EA $callerEA
}
}
end {}
}
function DeployLab {
param (
[parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string]
$arm,
[parameter(Mandatory = $true)]
$Lab,
[parameter(Mandatory = $true)]
$AsJob,
[parameter(Mandatory = $true)]
$Parameters,
[parameter(mandatory = $false)]
[switch]
$IsNewLab = $false
)
Write-debug "DEPLOY ARM TEMPLATE`n$arm`nWITH PARAMS: $(PrintHashtable $Parameters)"
$Name = $Lab.Name
$ResourceGroupName = $Lab.ResourceGroupName
$VmCreationSubnetPrefix = $null
$VmCreationResourceGroupName = $null
if (Get-Member -InputObject $Lab -Name VmCreationSubnetPrefix -MemberType Properties) {
$VmCreationSubnetPrefix = $Lab.VmCreationSubnetPrefix
}
if (Get-Member -InputObject $Lab -Name VmCreationResourceGroupName -MemberType Properties) {
$VmCreationResourceGroupName = $Lab.VmCreationResourceGroupName
}
if ($Name.Length -gt 40) {
$deploymentName = "LabDeploy_" + $Name.Substring(0, 40)
}
else {
$deploymentName = "LabDeploy" + $Name
}
Write-Verbose "Using deployment name $deploymentName with params`n $(PrintHashtable $Parameters)"
if(-not $IsNewLab) {
$existingLab = Get-AzureRmResource -Name $Name -ResourceGroupName $ResourceGroupName -ErrorAction SilentlyContinue
if (-not $existingLab) {
throw "'$Name' Lab already exists. This action is supposed to be performed on an existing lab."
}
}
$jsonPath = StringToFile($arm)
$sb = {
param($deploymentName, $Name, $ResourceGroupName, $VmCreationSubnetPrefix, $VmCreationResourceGroupName, $jsonPath, $Parameters, $workingDir, $justAz)
if($justAz) {
Enable-AzureRmAlias -Scope Local -Verbose:$false
Enable-AzContextAutosave -Scope Process | Out-Null
}
$deployment = New-AzureRmResourceGroupDeployment -Name $deploymentName -ResourceGroupName $ResourceGroupName -TemplateFile $jsonPath -TemplateParameterObject $Parameters
Write-debug "Deployment succeded with deployment of `n$deployment"
$lab = Get-AzureRmResource -Name $Name -ResourceGroupName $ResourceGroupName -ExpandProperties
if ($VmCreationSubnetPrefix) {
$labVnet = $lab | Get-AzDtlLabVirtualNetworks -ExpandedNetwork
$labVnet.Subnets[0].AddressPrefix = $VmCreationSubnetPrefix
$labVnet = Set-AzureRmVirtualNetwork -VirtualNetwork $labVnet
$lab = Get-AzureRmResource -Name $Name -ResourceGroupName $ResourceGroupName -ExpandProperties
}
if ($VmCreationResourceGroupName) {
# Import again the module, only if it hasn't already been imported
if (-not (Get-Command -Name "Get-AzDtlLab" -ErrorAction SilentlyContinue)) {
Import-Module "$workingDir\Az.DevTestLabs2.psm1"
}
$lab = Set-AzDtlVmCreationResourceGroup -Lab $lab -VmCreationResourceGroupName $VmCreationResourceGroupName
}
$lab
}
if($AsJob) {
Start-Job -ScriptBlock $sb -ArgumentList $deploymentName, $Name, $ResourceGroupName, $VmCreationSubnetPrefix, $VmCreationResourceGroupName, $jsonPath, $Parameters, $PWD, $justAz
} else {
Invoke-Command -ScriptBlock $sb -ArgumentList $deploymentName, $Name, $ResourceGroupName, $VmCreationSubnetPrefix, $VmCreationResourceGroupName, $jsonPath, $Parameters, $PWD, $justAz
}
}
function DeployVm {
param (
[parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string]
$arm,
[parameter(Mandatory = $true)]
$vm,
[parameter(Mandatory = $true)]
$AsJob,
[parameter(Mandatory = $true)]
$Parameters,
[parameter(mandatory = $false)]
[switch]
$IsNewVm = $false
)
Write-debug "DEPLOY ARM TEMPLATE`n$arm`nWITH PARAMS: $(PrintHashtable $Parameters)"
$Name = $vm.ResourceId.Split('/')[10]
$ResourceGroupName = $vm.ResourceGroupName
if ($Name.Length -gt 40) {
$deploymentName = "VMDeploy_" + $Name.Replace('/', '-').Substring(0, 40)
}
else {
$deploymentName = "VMDeploy" + $Name.Replace('/', '-')
}
Write-Verbose "Using deployment name $deploymentName with params`n $(PrintHashtable $Parameters)."
if(-not $IsNewVm) {
$existingVM = Get-AzureRmResource -Name $Name -ResourceGroupName $ResourceGroupName -ErrorAction SilentlyContinue
if (-not $existingVM) {
throw "'$Name' VM already exists. This action is supposed to be performed on an existing lab."
}
}
$jsonPath = StringToFile($arm)
$sb = {
param($deploymentName, $Name, $ResourceGroupName, $jsonPath, $Parameters, $justAz)
if($justAz) {
Enable-AzContextAutosave -Scope Process | Out-Null
}
$deployment = New-AzureRmResourceGroupDeployment -Name $deploymentName -ResourceGroupName $ResourceGroupName -TemplateFile $jsonPath -TemplateParameterObject $Parameters
Write-debug "Deployment succeded with deployment of `n$deployment"
Get-AzureRmResource -Name $Name -ResourceGroupName $ResourceGroupName -ExpandProperties
}
if($AsJob.IsPresent) {
Start-Job -ScriptBlock $sb -ArgumentList $deploymentName, $Name, $ResourceGroupName, $jsonPath, $Parameters, $justAz
} else {
Invoke-Command -ScriptBlock $sb -ArgumentList $deploymentName, $Name, $ResourceGroupName, $jsonPath, $Parameters, $justAz
}
}
#TODO: reduce function below to just get ErrorActionPreference
# Taken from https://gallery.technet.microsoft.com/scriptcenter/Inherit-Preference-82343b9d
function Get-CallerPreference
{
[CmdletBinding(DefaultParameterSetName = 'AllVariables')]
param (
[Parameter(Mandatory = $true)]
[ValidateScript({ $_.GetType().FullName -eq 'System.Management.Automation.PSScriptCmdlet' })]
$Cmdlet,
[Parameter(Mandatory = $true)]
[System.Management.Automation.SessionState]
$SessionState,
[Parameter(ParameterSetName = 'Filtered', ValueFromPipeline = $true)]
[string[]]
$Name
)
begin
{
$filterHash = @{}
}
process
{
if ($null -ne $Name)
{
foreach ($string in $Name)
{
$filterHash[$string] = $true
}
}
}
end
{
# List of preference variables taken from the about_Preference_Variables help file in PowerShell version 4.0
$vars = @{
'ErrorView' = $null
'FormatEnumerationLimit' = $null
'LogCommandHealthEvent' = $null
'LogCommandLifecycleEvent' = $null
'LogEngineHealthEvent' = $null
'LogEngineLifecycleEvent' = $null
'LogProviderHealthEvent' = $null
'LogProviderLifecycleEvent' = $null
'MaximumAliasCount' = $null
'MaximumDriveCount' = $null
'MaximumErrorCount' = $null
'MaximumFunctionCount' = $null
'MaximumHistoryCount' = $null
'MaximumVariableCount' = $null
'OFS' = $null
'OutputEncoding' = $null
'ProgressPreference' = $null
'PSDefaultParameterValues' = $null
'PSEmailServer' = $null
'PSModuleAutoLoadingPreference' = $null
'PSSessionApplicationName' = $null
'PSSessionConfigurationName' = $null
'PSSessionOption' = $null
'ErrorActionPreference' = 'ErrorAction'
'DebugPreference' = 'Debug'
'ConfirmPreference' = 'Confirm'
'WhatIfPreference' = 'WhatIf'
'VerbosePreference' = 'Verbose'
'WarningPreference' = 'WarningAction'
}
foreach ($entry in $vars.GetEnumerator())
{
if (([string]::IsNullOrEmpty($entry.Value) -or -not $Cmdlet.MyInvocation.BoundParameters.ContainsKey($entry.Value)) -and
($PSCmdlet.ParameterSetName -eq 'AllVariables' -or $filterHash.ContainsKey($entry.Name)))
{
$variable = $Cmdlet.SessionState.PSVariable.Get($entry.Key)
if ($null -ne $variable)
{
if ($SessionState -eq $ExecutionContext.SessionState)
{
Set-Variable -Scope 1 -Name $variable.Name -Value $variable.Value -Force -Confirm:$false -WhatIf:$false
}
else
{
$SessionState.PSVariable.Set($variable.Name, $variable.Value)
}
}
}
}
if ($PSCmdlet.ParameterSetName -eq 'Filtered')
{
foreach ($varName in $filterHash.Keys)
{
if (-not $vars.ContainsKey($varName))
{
$variable = $Cmdlet.SessionState.PSVariable.Get($varName)
if ($null -ne $variable)
{
if ($SessionState -eq $ExecutionContext.SessionState)
{
Set-Variable -Scope 1 -Name $variable.Name -Value $variable.Value -Force -Confirm:$false -WhatIf:$false
}
else
{
$SessionState.PSVariable.Set($variable.Name, $variable.Value)
}
}
}
}
}
} # end
} # function Get-CallerPreference
# Convert a string to a file so that it can be passed to functions that take a path. Assumes temporary files are deleted by the OS eventually.
function StringToFile([string] $text) {
$tmp = New-TemporaryFile
Set-Content -Path $tmp.FullName -Value $text
return $tmp.FullName
}
function GetComputeVm($vm) {
try {
if ($vm.Properties.computeId) {
# Instead of another round-trip to Azure, we parse the Compute ID to get the VM Name & Resource Group
if ($vm.Properties.computeId -match "\/subscriptions\/(.*)\/resourceGroups\/(.*)\/providers\/Microsoft\.Compute\/virtualMachines\/(.*)$") {
# For successful match, powershell stores the matches in "$Matches" array
$vmResourceGroupName = $Matches[2]
$vmName = $Matches[3]
} else {
# Unable to parse the resource Id, so let's do the additional round trip to Azure
$vm = Get-AzureRmResource -ResourceId $vm.Properties.computeId
$vmResourceGroupName = $vm.ResourceGroupName
$vmName = $vm.Name
}
return Get-AzureRmVm -ResourceGroupName $vmResourceGroupName -Name $vmName -Status
}
}
catch {
Write-Information "DevTest Lab VM $($vm.Name) in RG $($vm.ResourceGroupName) has no associated compute VM"
}
# In this case, the ComputeId isn't set or doesn't resolve to a VM
# this is a busted VM (compute VM was deleted out from under the DTL VM)
return $null
}
#endregion
#region LAB ACTIONS
function New-AzDtlLab {
[CmdletBinding()]
param(
[parameter(Mandatory=$true, ValueFromPipelineByPropertyName = $true, HelpMessage="Name of the lab to create.")]
[ValidateLength(1,50)]
[ValidateNotNullOrEmpty()]
[string] $Name,
[parameter(Mandatory=$true, ValueFromPipelineByPropertyName = $true, HelpMessage="Name of the resource group where to create the lab. It must already exist.")]
[ValidateNotNullOrEmpty()]
[string] $ResourceGroupName,
[parameter(Mandatory=$false,HelpMessage="The resource group in which all new lab virtual machines will be created. To let DevTest Labs manage resource group creation, set this value to null.")]
[string] $VmCreationResourceGroupName,
[parameter(Mandatory=$false,HelpMessage="IP address prefix (CIDR notation) within 10.0.0.0/20 reserved for VMs creation. (e.g 10.0.0.0/21, 10.)")]
[ValidateNotNullOrEmpty()]
[string] $VmCreationSubnetPrefix,
[parameter(Mandatory=$false,HelpMessage="Run the command in a separate job.")]
[switch] $AsJob = $False
)
begin {. BeginPreamble}
process {
try {
# We could create it, if it doesn't exist, but that would complicate matters as we'd need to take a location as well as parameter
# Choose to keep it as simple as possible to start with.
Get-AzureRmResourceGroup -Name $ResourceGroupName -ErrorAction Stop | Out-Null
$CIDRIPv4Regex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/(3[0-2]|[1-2][0-9]|[0-9]))$"
if ($VmCreationSubnetPrefix -and !($VmCreationSubnetPrefix -match $CIDRIPv4Regex)) {
throw "Not a valid CIDR IPv4 address range"
}
$params = @{
newLabName = $Name
}
# Need to create this as DeployLab takes a lab, which works better in all other cases
$Lab = [pscustomobject] @{
Name = $Name
ResourceGroupName = $ResourceGroupName
}
if ($VmCreationSubnetPrefix) {
$Lab | Add-member -Name 'VmCreationSubnetPrefix' -Value $VmCreationSubnetPrefix -MemberType NoteProperty
}
if ($VmCreationResourceGroupName) {
$Lab | Add-member -Name 'VmCreationResourceGroupName' -Value $VmCreationResourceGroupName -MemberType NoteProperty
}
# Taken from official sample here: https://github.com/Azure/azure-devtestlab/blob/master/Samples/101-dtl-create-lab/azuredeploy.json
@"
{
"`$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"newLabName": {
"type": "string",
"metadata": {
"description": "The name of the new lab instance to be created"
}
}
},
"variables": {
"labVirtualNetworkName": "[concat('Dtl', parameters('newLabName'))]"
},
"resources": [
{
"apiVersion": "2018-10-15-preview",
"type": "Microsoft.DevTestLab/labs",
"name": "[parameters('newLabName')]",
"location": "[resourceGroup().location]",
"resources": [
{
"apiVersion": "2018-10-15-preview",
"name": "[variables('labVirtualNetworkName')]",
"type": "virtualNetworks",
"dependsOn": [
"[resourceId('Microsoft.DevTestLab/labs', parameters('newLabName'))]"
]
},
{
"apiVersion": "2018-10-15-preview",
"name": "Public Environment Repo",
"type": "artifactSources",
"location": "[resourceGroup().location]",
"dependsOn": [
"[resourceId('Microsoft.DevTestLab/labs', parameters('newLabName'))]"
],
"properties": {
"status": "Enabled"
}
}
]
}
],
"outputs": {
"labId": {
"type": "string",
"value": "[resourceId('Microsoft.DevTestLab/labs', parameters('newLabName'))]"
}
}
}
"@ | DeployLab -Lab $Lab -AsJob $AsJob -IsNewLab -Parameters $Params
}
catch {
Write-Error -ErrorRecord $_ -EA $callerEA
}
}
end {
}
}
function Remove-AzDtlLab {
[CmdletBinding()]
param(
[parameter(Mandatory=$true,HelpMessage="Lab object to remove.", ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
$Lab,
[parameter(Mandatory=$false,HelpMessage="Run the command in a separate job.")]
[switch] $AsJob = $False
)
begin {. BeginPreamble}
process {
try {
foreach($l in $Lab) {
$resId = $l.ResourceId
Write-Verbose "Started removal of lab $resId."
if($AsJob.IsPresent) {
Remove-AzureRmResource -ResourceId $resId -AsJob -Force
} else {
Remove-AzureRmResource -ResourceId $resId -Force
}
Write-Verbose "Removed lab $resId."
}
} catch {
Write-Error -ErrorRecord $_ -EA $callerEA
}
}
end {}
}
function Add-AzDtlLabTags {
[CmdletBinding()]
param(
[parameter(Mandatory=$true, ValueFromPipeline=$true, HelpMessage="Lab object to set Shared Image Gallery")]
[ValidateNotNullOrEmpty()]
$Lab,
[parameter(Mandatory=$true,HelpMessage="The tags to set on the lab and it's associated resources like this: @{'ProjectCode'='123456';'BillingCode'='654321'}")]
[Hashtable] $tags,
[Parameter(Mandatory=$false, HelpMessage="Also tag the lab's resource group?")]
[bool] $tagLabsResourceGroup,
[parameter(Mandatory = $false)]
[switch] $AsJob
)
begin {. BeginPreamble}
process {
try{
$StartJobIfNeeded = {
param($Resource, $IsResourceGroup, $tags, $AsJob)
$tagSb = {
param($Resource, $IsResourceGroup, $newTags, $justAz)
Enable-AzureRmAlias -Scope Local -Verbose:$false
Enable-AzContextAutosave -Scope Process | Out-Null
if ($IsResourceGroup) {
# Apply the unified tags back to Azure
Set-AzureRmResourceGroup -Id $Resource.ResourceId -Tag $newTags | Out-Null
}
else {
# Apply the unified tags back to Azure
Set-AzureRmResource -ResourceId $Resource.ResourceId -Tag $newTags -Force | Out-Null
}
return
}
function Unify-Tags {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[AllowNull()]
[hashtable] $destinationTagList,
[Parameter(Mandatory=$true)]
[AllowNull()]
[hashtable] $sourceTagList
)
# if the destination doesn't have any tags, just apply the whole set of tags from the source
if ($destinationTagList -eq $null) {
if ($sourceTagList -ne $null) {
$finalTagList = $sourceTagList.Clone()
}
else {
$finalTagList = $null
}
}
else {
# The destination list has tags, let's compare each one to make sure none are missing
$finalTagList = $destinationTagList.Clone()
# If the source list of tags isn't null, lets merge the tags in
if ($sourceTagList -ne $null) {
foreach ($sourceTag in $sourceTagList.GetEnumerator()) {
# Does the dest contain the Tag?
if ($finalTagList.Contains($sourceTag.Name)) {
# If there's a tag with the same name and the value is different we should fix it
if ($finalTagList[$sourceTag.Name] -ne $sourceTag.Value) {
$finalTagList[$sourceTag.Name] = $sourceTag.Value
}
}
else {
# destination doesn't contain the tag, let's add it
$finalTagList.Add($sourceTag.Name, $sourceTag.Value)
}
}
}
}
$finalTagList
}
# From here: https://gist.github.com/dbroeglin/c6ce3e4639979fa250cf
function Compare-Hashtable {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[Hashtable]$Left,
[Parameter(Mandatory = $true)]
[Hashtable]$Right
)
function New-Result($Key, $LValue, $Side, $RValue) {
New-Object -Type PSObject -Property @{
key = $Key
lvalue = $LValue
rvalue = $RValue
side = $Side
}
}
[Object[]]$Results = $Left.Keys | % {
if ($Left.ContainsKey($_) -and !$Right.ContainsKey($_)) {
New-Result $_ $Left[$_] "<=" $Null
} else {
$LValue, $RValue = $Left[$_], $Right[$_]
if ($LValue -ne $RValue) {
New-Result $_ $LValue "!=" $RValue
}
}
}
$Results += $Right.Keys | % {
if (!$Left.ContainsKey($_) -and $Right.ContainsKey($_)) {
New-Result $_ $Null "=>" $Right[$_]
}
}
$Results
}
# If we have only the resource Id, let's get the full object
if ($Resource.GetType().Name -eq "String" -and $IsResourceGroup -eq $true) {
$Resource = Get-AzureRmResourceGroup -Id $Resource
}
if ($Resource.GetType().Name -eq "String" -and $IsResourceGroup -eq $false) {
$Resource = Get-AzureRmResource -ResourceId $Resource
}
# Check to see if the resource already has all the tags
$newTags = (Unify-Tags $Resource.Tags $tags)
# If we don't have any source tags, just write the new tags
if (-not (Get-Member -InputObject $Resource -Name 'Tags') -or
(($Resource.Tags | Measure-Object).Count -eq 0) -or
(Compare-Hashtable -Left $Resource.Tags -Right $newTags)) {
if($AsJob) {
Start-Job -ScriptBlock $tagSb -ArgumentList $Resource, $IsResourceGroup, $newTags, $justAz
} else {
Invoke-Command -ScriptBlock $tagSb -ArgumentList $Resource, $IsResourceGroup, $newTags, $justAz
}
}
else {
Write-Verbose "Tags are the same, can skip for ResourceId $($Resource.ResourceId)!"
}
}
# Tag the resource group if the user wants
if ($tagLabsResourceGroup) {
$labrg = Get-AzureRmResourceGroup -Name $Lab.ResourceGroupName
Invoke-Command -ScriptBlock $StartJobIfNeeded -ArgumentList $labrg, $true, $tags, $AsJob
}
# Get the lab resource and tag it
$labObj = Get-AzureRmResource -Name $Lab.Name -ResourceGroupName $Lab.ResourceGroupName -ResourceType "Microsoft.DevTestLab/labs"
Invoke-Command -ScriptBlock $StartJobIfNeeded -ArgumentList $labObj, $false, $tags, $AsJob
# Get the DTL VMs and tag them
Get-AzureRmResource -ResourceGroupName $Lab.ResourceGroupName -ResourceType "Microsoft.DevTestLab/labs/VirtualMachines" | Where-Object {
$_.Name.StartsWith($Lab.Name + "/")
} | ForEach-Object {
Invoke-Command -ScriptBlock $StartJobIfNeeded -ArgumentList $_, $false, $tags, $AsJob
}
# Find all the resources associated with this lab (only proceed if we found the lab)
if ($labObj.Properties.uniqueIdentifier) {
Get-AzureRmResource -TagName hidden-DevTestLabs-LabUId -TagValue $labObj.Properties.uniqueIdentifier `
| ForEach-Object {
Invoke-Command -ScriptBlock $StartJobIfNeeded -ArgumentList $_, $false, $tags, $AsJob
if ($_.ResourceType -eq 'Microsoft.Compute/virtualMachines') {
# We need to get the disks on the VM and tag those - disks from specialized images don't have a hidden tag
# But the other resources (load balancer, network interface, public IPs, etc.) are all tagged above
$vm = Get-AzureRmResource -ResourceId $_.ResourceId
# Tag the compute's resource group assuming it's not the lab's RG
if ($vm.ResourceGroupName -ne $labObj.ResourceGroupName) {
$vmRg = Get-AzureRmResourceGroup -Name $vm.ResourceGroupName
Invoke-Command -ScriptBlock $StartJobIfNeeded -ArgumentList $vmRg, $true, $tags, $AsJob
}
# Add tags to the OS disk (VMs should always have an OS disk
Invoke-Command -ScriptBlock $StartJobIfNeeded -ArgumentList $vm.Properties.storageProfile.osDisk.managedDisk.id, $false, $tags, $AsJob
# Add Tags to the data disks
$vm.Properties.storageProfile.dataDisks | ForEach-Object {
Invoke-Command -ScriptBlock $StartJobIfNeeded -ArgumentList $_.managedDisk.id, $false, $tags, $AsJob
}
}
}
}
}
catch {
Write-Error -ErrorRecord $_ -EA $callerEA
}
}
end {
}
}
function Set-AzDtlLabIpPolicy {
[CmdletBinding()]
param(
[parameter(Mandatory=$true, ValueFromPipeline=$true, HelpMessage="Lab to query for Shared Image Gallery")]
[ValidateNotNullOrEmpty()]
$Lab,
[parameter(Mandatory=$false, HelpMessage="Name of the subnet to update the properties. If left out, all subnets are updated")]
[string]
$SubnetName,
[parameter(Mandatory=$true, HelpMessage="Public=separate IP Address, Shared=load balancers optimizes IP Addresses, Private=No public IP address.")]
[Validateset('Public','Private', 'Shared')]
[string]
$IpConfig = 'Shared'
)
begin {. BeginPreamble}
process {
try{
$sharedIpConfig = @"
{
"allowedPorts": [
{
"transportProtocol" : "Tcp",
"backendPort" : "3389"
},
{
"transportProtocol" : "Tcp",
"backendPort" : "22"
}
]
}
"@ | ConvertFrom-Json
Write-verbose "Retrieving Virtual Network for lab $($Lab.Name) ..."
$vnets = Get-AzResource -Name $Lab.Name -ResourceGroupName $Lab.ResourceGroupName -ResourceType 'Microsoft.DevTestLab/labs/virtualnetworks' -ODataQuery '$expand=Properties($expand=externalSubnets)' -ApiVersion 2018-10-15-preview
# Iterate through the vnets for all the subnets
foreach ($vnet in $vnets) {
# There is a chance that subnet overrides doesn't exist. This seems to happen if:
# 1) We get to the lab before DTL has fully populated the objects, or
# 2) If the DTL VM object is created before the underlying VNet subnets are (ordering)
# If they're missing, let's generate the defaults for subnetOverrides
if (-not ($vnet.Properties.PSObject.Properties.Name -match "subnetOverrides")) {
$subnetOverrides = [array] ($vnet.Properties.externalSubnets | ForEach-Object {
[PSCustomObject] @{
resourceId = $_.id
labSubnetName = $_.name
useInVmCreationPermission = "Allow"
usePublicIpAddressPermission = "Allow"
}
})
Add-Member -InputObject $vnet.Properties -Name "subnetOverrides" -MemberType NoteProperty -Value $subnetOverrides
}
# Iterate through the subnets and set the properties appropriately
foreach ($subnet in $vnet.Properties.subnetOverrides) {
# Only update if it matches the subnet name/subnetname is missing AND if this is a VNet used for VM Creation
if ((-not $SubnetName -or ($subnet.labSubnetName -like $SubnetName)) -and ($subnet.useInVmCreationPermission -eq "Allow")) {
if ($IpConfig -eq 'Shared') {
if ($subnet.PSObject.Properties.Name -match "sharedPublicIpAddressConfiguration") {
$subnet.sharedPublicIpAddressConfiguration = $sharedIpConfig
}
else {
Add-Member -InputObject $subnet -MemberType NoteProperty -Name "sharedPublicIpAddressConfiguration" -Value $sharedIpConfig
}
$subnet.usePublicIpAddressPermission = $false
}
elseif ($IpConfig -eq 'Public') {
if ($subnet.PSObject.Properties.Name -match "sharedPublicIpAddressConfiguration") {
$subnet.PSObject.Properties.Remove("sharedPublicIpAddressConfiguration")
}
$subnet.usePublicIpAddressPermission = $true
}
elseif ($IpConfig -eq 'Private') {
if ($subnet.PSObject.Properties.Name -match "sharedPublicIpAddressConfiguration") {
$subnet.PSObject.Properties.Remove("sharedPublicIpAddressConfiguration")
}
$subnet.usePublicIpAddressPermission = $false
}
}
}
# Push this VNet back to Azure
Set-AzResource -ResourceId $vnet.ResourceId -Properties $vnet.Properties -Force
}
# Return the lab to continue in the pipeline
return $Lab
}
catch {
Write-Error -ErrorRecord $_ -EA $callerEA
}
}
end {
}
}
function Get-AzDtlLabSharedImageGallery {
[CmdletBinding()]
param(
[parameter(Mandatory=$true, ValueFromPipeline=$true, HelpMessage="Lab to query for Shared Image Gallery")]
[ValidateNotNullOrEmpty()]
$Lab,
[parameter(Mandatory=$false,HelpMessage="Also return images")]
[switch] $IncludeImages = $false
)
begin {. BeginPreamble}
process {
try{
# Get the shared image gallery
Write-Verbose "Checking for the shared image gallery resource for lab '$($lab.Name)'"
$sig = Get-AzureRmResource -ResourceGroupName $Lab.ResourceGroupName -ResourceType 'Microsoft.DevTestLab/labs/sharedGalleries' -ResourceName $Lab.Name -ApiVersion 2018-10-15-preview
# Get all the images too and return the whole thing - if $sig is null, we don't return anything (no pipeline object)
if ($sig) {
if ($IncludeImages) {
# Get the images in the shared image gallery
$sigImages = $sig | Get-AzDtlLabSharedImageGalleryImages
# Add the images to the shared image gallery object
$sig | Add-Member -MemberType NoteProperty -Name "Images" -Value $sigimages
}
return $sig
}
}
catch {
Write-Error -ErrorRecord $_ -EA $callerEA
}
}
end {
}