-
Notifications
You must be signed in to change notification settings - Fork 601
Expand file tree
/
Copy pathAz.DevTestLabs2.psm1
More file actions
3266 lines (2847 loc) · 117 KB
/
Az.DevTestLabs2.psm1
File metadata and controls
3266 lines (2847 loc) · 117 KB
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-AzureRmContextAutosave -Scope CurrentUser -erroraction silentlycontinue
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-AzureRmContextAutosave -Scope CurrentUser -erroraction silentlycontinue
}
# 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 -Name $Name -EA SilentlyContinue
} else { #Proper RG, wild name
Get-AzureRmResource -ExpandProperties -resourcetype $ResourceType -ResourceGroupName $ResourceGroupName -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
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, $jsonPath, $Parameters, $justAz)
if($justAz) {
Enable-AzureRmAlias -Scope Local -Verbose:$false
}
$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) {
Start-Job -ScriptBlock $sb -ArgumentList $deploymentName, $Name, $ResourceGroupName, $jsonPath, $Parameters, $justAz
} else {
Invoke-Command -ScriptBlock $sb -ArgumentList $deploymentName, $Name, $ResourceGroupName, $jsonPath, $Parameters, $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-AzureRmAlias -Scope Local -Verbose:$false
}
$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="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
$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
}
# 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 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 {
}
}
function Remove-AzDtlLabSharedImageGallery {
[CmdletBinding()]
param(
[parameter(Mandatory=$true, ValueFromPipeline=$true, HelpMessage="DevTest Labs Shared Image Gallery object to remove from the lab")]
[ValidateNotNullOrEmpty()]
$SharedImageGallery
)
begin {. BeginPreamble}
process {
try{
Remove-AzureRmResource -ResourceId $SharedImageGallery.ResourceId -ApiVersion 2018-10-15-preview -Force
}
catch {
Write-Error -ErrorRecord $_ -EA $callerEA
}
}
end {
}
}
function Set-AzDtlLabSharedImageGallery {
[CmdletBinding()]
param(
[parameter(Mandatory=$true, ValueFromPipeline=$true, HelpMessage="Lab object to set Shared Image Gallery")]
[ValidateNotNullOrEmpty()]
$Lab,
[parameter(Mandatory=$true,HelpMessage="The DevTest Labs name for the shared image gallery")]
[string] $Name,
[parameter(Mandatory=$true,HelpMessage="Full ResourceId of the Shared Image Gallery to attach to the lab")]
[string] $ResourceId,
[parameter(Mandatory=$false,HelpMessage="Set to true to allow all images to be used as VM bases, set to false to control image-by-image which ones are allowed")]
[bool] $AllowAllImages = $true
)
begin {. BeginPreamble}
process {
try{
if ($AllowAllImages) {
$status = "Enabled"
} else {
$status = "Disabled"
}
$propertiesObject = @{
GalleryId = $ResourceId
allowAllImages = $status
}
# Add a shared image gallery
$result = New-AzureRmResource -Location $Lab.Location `
-ResourceGroupName $Lab.ResourceGroupName `
-properties $propertiesObject `
-ResourceType 'Microsoft.DevTestLab/labs/sharedGalleries' `
-ResourceName ($Lab.Name + '/' + $Name) `
-ApiVersion 2018-10-15-preview `
-Force
# following the pipeline pattern, return the shared image gallery object on the pipeline
return ($Lab | Get-AzDtlLabSharedImageGallery)
}
catch {
Write-Error -ErrorRecord $_ -EA $callerEA
}
}
end {
}
}
function Get-AzDtlVirtualNetworks {
[CmdletBinding()]
param(
[parameter(Mandatory=$true, ValueFromPipeline=$true, HelpMessage="Lab object to get the Virtual Network from")]
[ValidateNotNullOrEmpty()]
$Lab,
[parameter(Mandatory=$false, ValueFromPipeline=$true, HelpMessage="If set, get the Expanded Resource from the std VNet object")]
$ExpandResource
)
begin {. BeginPreamble}
process {
try {
foreach($lab in $Lab) {
$lab = $lab | Get-AzDtlLab
$dtlLabVNets = Get-AzureRmResource `
-ResourceGroupName $lab.ResourceGroupName `
-ResourceType Microsoft.DevTestLab/labs/virtualnetworks `
-ResourceName $lab.Name `
-ApiVersion 2018-09-15
if ($ExpandResource) {
foreach($dtlLabVNet in $dtlLabVNets) {
Get-AzureRmVirtualNetwork -ResourceGroupName $dtlLabVNet.ResourceGroupName -Name $dtlLabVNet.Name -ExpandResource $ExpandResource
}
}
}
} catch {
Write-Error -ErrorRecord $_ -EA $callerEA
}
}
end {}
}
function Get-AzDtlLabSharedImageGalleryImages {
[CmdletBinding()]
param(
[parameter(Mandatory=$true, ValueFromPipeline=$true, HelpMessage="DevTest Labs Shared Image Gallery object to get images")]
[ValidateNotNullOrEmpty()]
$SharedImageGallery
)
begin {. BeginPreamble}
process {
try{
$sigimages = Get-AzureRmResource -ResourceId ($SharedImageGallery.ResourceId + "/sharedimages") `
-ApiVersion 2018-10-15-preview `
| ForEach-Object {
Add-Member -InputObject $_.Properties -MemberType NoteProperty -Name ResourceId -Value $_.ResourceId
$_.Properties.PSObject.Properties.Remove('uniqueIdentifier')
# Return properties on the pipeline
$_.Properties
}
return $sigimages
}
catch {
Write-Error -ErrorRecord $_ -EA $callerEA
}
}
end {
}
}
function UpdateSharedImageGalleryImage ($SigResourceId, $ImageName, $OsType, $ImageType, $Status) {
$propertiesObject = @{
definitionName = $ImageName
enableState = $Status
osType = $OsType
ImageType = $ImageType
}
Set-AzureRmResource -ResourceId ($SigResourceId + "/sharedImages/" + $ImageName) `
-ApiVersion 2018-10-15-preview `
-Properties $propertiesObject `
-Force | Out-Null
}
function Set-AzDtlLabSharedImageGalleryImages {
[CmdletBinding()]
param(
[parameter(Mandatory=$true, ParameterSetName = "Default", ValueFromPipeline=$true, HelpMessage="Shared Image Gallery object with Images property populated")]
[parameter(Mandatory=$true, ParameterSetName = "SingleImageChange", ValueFromPipeline=$true, HelpMessage="Shared Image Gallery object")]
[ValidateNotNullOrEmpty()]
$SharedImageGallery,
[parameter(Mandatory=$true, ParameterSetName = "SingleImageChange", HelpMessage="Image Name for the image to change the enabled/disabled setting on")]
[string] $ImageName,
[parameter(Mandatory=$true, ParameterSetName = "SingleImageChange", HelpMessage="The type of OS for this particular image")]
[ValidateSet('Windows','Linux')]
[string] $OsType,
[parameter(Mandatory=$true, ParameterSetName = "SingleImageChange", HelpMessage="Image Name for the image to change the enabled/disabled setting on")]
[string] $ImageType,
[parameter(Mandatory=$true, ParameterSetName = "SingleImageChange", HelpMessage="Should the image be enabled (true) or disabled (false)")]
[bool] $Enabled
)
begin {. BeginPreamble}
process {
try{
# If we're specifying a state for a specific image, we assume that the gallery should be
# set with the "allowAllImages" property to false - let's fix if needed
if ($SharedImageGallery.Properties.allowAllImages -eq "Enabled") {
$propertiesObject = @{
GalleryId = $SharedImageGallery.Properties.galleryId
allowAllImages = "Disabled"
}
# Update the SIG using ResourceID
$result = Set-AzureRmResource -ResourceId $SharedImageGallery.ResourceId `
-Properties $propertiesObject `
-ApiVersion 2018-10-15-preview `
-Force
}
if ($ImageName) {
# If we're looking at a single image, we handle it directly
if ($Enabled) {
$status = "Enabled"
} else {
$status = "Disabled"
}
UpdateSharedImageGalleryImage $SharedImageGallery.ResourceId $ImageName $OsType $ImageType $status
} else {
# First ensure the Images property is correctly set
if ($SharedImageGallery.Images) {
# Iterate through all the images and set each one
foreach ($img in $SharedImageGallery.Images) {
UpdateSharedImageGalleryImage $SharedImageGallery.ResourceId $img.definitionName $img.osType $img.imageType $img.enableState
}
} else {
Write-Error '$SharedImageGallery.Images property must be set or ImageName & Enabled must be set'
}
}
# following the pipeline pattern, return the shared image gallery object on the pipeline
return $SharedImageGallery
}
catch {
Write-Error -ErrorRecord $_ -EA $callerEA
}
}
end {
}
}
#endregion
#region VM ACTIONS
function Get-AzDtlVm {
[CmdletBinding()]
param(
[parameter(Mandatory=$true,HelpMessage="Lab object to retrieve VM from.", ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
$Lab,
[parameter(Mandatory=$false,HelpMessage="Name of the VMs to retrieve. This parameter supports wildcards at the beginning and/or end of the string.")]
[ValidateNotNullOrEmpty()]
[string]
$Name = "*",
[parameter(Mandatory=$false,HelpMessage="Status filter for the vms to retrieve. This parameter supports wildcards at the beginning and/or end of the string.")]
[ValidateSet('Starting', 'Running', 'Stopping', 'Stopped', 'Failed', 'Restarting', 'ApplyingArtifacts', 'UpgradingVmAgent', 'Creating', 'Deleting', 'Corrupted', 'Any')]
[string]
$Status = 'Any',
[parameter(Mandatory=$false,HelpMessage="Check underlying compute for complete status")]
[switch] $ExtendedStatus=$false
)
begin {. BeginPreamble}
process {
try {
foreach($l in $Lab) {
$ResourceGroupName = $l.ResourceGroupName
$LabName = $l.Name
Write-verbose "Retrieving $Name VMs for lab $LabName in $ResourceGroupName."
# Need to query client side to support wildcard at start of name as well (but this is bad as potentially many vms are involved)
# Also notice silently continue for errors to return empty set for composibility
# TODO: is there a clever way to make this less expensive? I.E. prequery without -ExpandProperties and then use the result to query again.
$vms = MyGetResourceVm -Name "$Name" -LabName $LabName -ResourceGroupName $ResourceGroupName
if($vms -and ($Status -ne 'Any')) {
return $vms | Where-Object { $Status -eq (Get-AzDtlVmStatus $_ -ExtendedStatus:$ExtendedStatus)}
} else {
if ($ExtendedStatus) {
foreach($vm in $vms) {
Add-Member -InputObject $vm.Properties -MemberType NoteProperty -Name "Status" -Value $(Get-AzDtlVmStatus $vm -ExtendedStatus:$ExtendedStatus)
}
}
return $vms
}
}
} catch {
Write-Error -ErrorRecord $_ -EA $callerEA
}
}
end {}
}
function Get-AzDtlVmStatus {
[CmdletBinding()]
param(
[parameter(Mandatory=$true,HelpMessage="VM to get status for.", ValueFromPipeline=$true)]
[ValidateNotNullOrEmpty()]
$Vm,
[parameter(Mandatory=$false,HelpMessage="Check underlying compute for complete status")]
[switch] $ExtendedStatus=$false
)
begin {. BeginPreamble}
process {
try {
foreach($v in $Vm) {
# If the DTL VM has provisioningState equal to "Succeeded", we need to check the compute VM state
if ($v.Properties.provisioningState -eq "Succeeded") {
if ($ExtendedStatus) {
$computeVm = GetComputeVm($v)
if ($computeVm) {
$computeProvisioningStateObj = $computeVm.Statuses | Where-Object {$_.Code.Contains("ProvisioningState")} | Select-Object Code -First 1
$computeProvisioningState = $null
if ($computeProvisioningStateObj) {
$computeProvisioningState = $computeProvisioningStateObj.Code.Replace("ProvisioningState/", "")
}
$computePowerStateObj = $computeVm.Statuses | Where-Object {$_.Code.Contains("PowerState")} | Select-Object Code -First 1
$computePowerState = $null
if ($computePowerStateObj) {
$computePowerState = $computePowerStateObj.Code.Replace("PowerState/", "")
}
# if we have a powerstate, we return the pretty string for it. This should match the DTL UI
if ($computePowerState) {
if ($computePowerState -eq "deallocating") {
return "Stopping"
} elseif ($computePowerState -eq "deallocated") {
return "Stopped"
} elseif ($computePowerState -eq "running") {
return "Running"
} elseif ($computePowerState -eq "starting") {
return "Starting"
} elseif ($computePowerState -eq "stopped") {
return "Stopped"
} elseif ($computePowerState -eq "stopping") {
return "Stopping"
} else {
# if we have a powerstate we don't recognize, let's return "Updating"
return "Updating"
}
} else {
# No power state, we return the provisioning state
if ($computeProvisioningState -eq "updating") {
return "Updating"
} elseif ($computeProvisioningState -eq "failed") {
return "Failed"
} elseif ($computeProvisioningState -eq "deleting") {
return "Deleting"
} else {
return $computeProvisioningState
}
}
} else {
# Compute VM is null, means we have a failed VM
return "Corrupted"
}
} else {
return $v.Properties.lastKnownPowerState