Framework/Configurations/Migration/Migration.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
Set-StrictMode -Version Latest

class MigrationHelper 
{
    static [StorageHelper] $StorageAccountInstance;
    
    static [void] StartMigration([SubscriptionContext] $subscriptionContext, [PSObject] $InvocationContext, [string] $AzureADAppName)
    {
        #TODO Telemetry
        [AIOrgTelemetryHelper]::CommonProperties= $subscriptionContext
        [PSObject] $MigrationOutput = @{}
        [bool] $ErrorOccurred = $false;
        try
        {
            [AIOrgTelemetryHelper]::PublishEvent("AzSK Migration Started",$null, $null)
            Write-Host ([Constants]::DoubleDashLine + "`r`nUpdating your current subscription with latest policies along with migration of existing resources...`r`n" + [Constants]::DoubleDashLine) -ForegroundColor Cyan;

            #region clear any existing locks
            try
            {
                Write-Host ("Checking if there are any resource locks on old RG...") -ForegroundColor Yellow;

                $azsdkRGScope = "/subscriptions/$($subscriptionContext.SubscriptionId)/resourceGroups/$([OldConstants]::AzSDKRGName)"
                $resourceLocks = @();
                $resourceLocks += Get-AzureRmResourceLock -Scope $azsdkRGScope -ErrorAction Stop
                if($resourceLocks.Count -gt 0)
                {
                    $resourceLocks | ForEach-Object {
                        Remove-AzureRmResourceLock -LockId $_.LockId -Force
                    }
                    Write-Host ("Successfully removed the locks on old resource group.") -ForegroundColor Green;
                }
                else
                {
                    Write-Host ("No locks found on old resource group.") -ForegroundColor Green;
                }
                $MigrationOutput.LockRemoval = "Success"
            }
            catch
            {
                Write-Host "An error occurred during removal of locks on old resource group: [$([OldConstants]::AzSDKRGName)]" -ForegroundColor Red
                [AIOrgTelemetryHelper]::PublishEvent("AzSK Migration Error",@{ "StageName"= "Resource Group Lock"; "ErrorRecord" = ($_ | Out-String); "MigrationStatus"= ($MigrationOutput | Out-String) }, $null)
                $MigrationOutput.LockRemoval = "Failed. Message[$_]"
                $ErrorOccurred = $true;
                throw;
            }
            #endregion

            #region capture the existing information
            $vars = $null
            $oldResourceGroupLocation = [ConfigurationManager]::GetAzSKConfigData().AzSKLocation;
            $scanIntervalInHours = 24;
            try
            {
                Write-Host ("Extracting current data from old resources...") -ForegroundColor Yellow;

                $oldRg = Get-AzureRmResourceGroup -Name $([OldConstants]::AzSDKRGName) -ErrorAction SilentlyContinue
                if($oldRg)
                {
                    $oldResourceGroupLocation = $oldRg.Location;
                }
                $vars = Get-AzureRmAutomationVariable -ResourceGroupName $([OldConstants]::AzSDKRGName) -AutomationAccountName $([OldConstants]::AutomationAccountName) -ErrorAction SilentlyContinue
                $migrateCA = $true;
                if(($vars | Measure-Object).Count -eq 0)
                {
                    $migrateCA = $false;
                }
                $newRGName = [ConfigurationManager]::GetAzSKConfigData().AzSKRGName;
                if($migrateCA)
                {
                    $schedule = Get-AzureRmAutomationSchedule -Name $([Constants]::ScheduleName) -ResourceGroupName $newRGName -AutomationAccountName $([Constants]::AutomationAccountName) -ErrorAction SilentlyContinue
                    if($null -ne $schedule -and $schedule.Frequency -eq 'Hour')
                    {
                        $scanIntervalInHours = $schedule.Interval
                    }
                }

                Write-Host ("Successfully completed extracting current data from old resources.") -ForegroundColor Green;
                $MigrationOutput.CurrentDataExtraction = "Success"                
            }
            catch{
                Write-Host "An error while fetching the current data" -ForegroundColor Red
                [AIOrgTelemetryHelper]::PublishEvent("AzSK Migration Error",@{ "StageName"= "Capture Existing Metadata"; "ErrorRecord" = ($_ | Out-String); "MigrationStatus"= ($MigrationOutput | Out-String) }, $null)
                $MigrationOutput.CurrentDataExtraction = "Failed. Message[$_]"
                $ErrorOccurred = $true;
                throw;
            }
            #endregion

            #region creating new resources
            try
            {
                Write-Host ("Creating new resources...") -ForegroundColor Yellow;            
                [MigrationHelper]::SetupAzSKResources($subscriptionContext.SubscriptionId, $oldResourceGroupLocation)
                Write-Host ("Successfully completed creating new resources.") -ForegroundColor Green;
                $MigrationOutput.ResourceCreation = "Success"
            }
            catch{
                Write-Host "An error occurred during creation of new resources. See migration log for details." -ForegroundColor Red
                [AIOrgTelemetryHelper]::PublishEvent("AzSK Migration Error",@{ "StageName"= "Resource Setup"; "ErrorRecord" = ($_ | Out-String); "MigrationStatus"= ($MigrationOutput | Out-String) }, $null)
                $MigrationOutput.ResourceCreation = "Failed. Message[$_]"
                $ErrorOccurred = $true;
                throw;
            }
            #endregion

            #region alerts migration
            try
            {
                Write-Host ("Creating new alerts and cleaning up old ones...") -ForegroundColor Yellow;
                [MigrationHelper]::MigrateAlerts($subscriptionContext.SubscriptionId, $InvocationContext);
                Write-Host ("Successfully completed creating new alerts.") -ForegroundColor Green;
                $MigrationOutput.AlertsMigration = "Success"
            }
            catch
            {
                Write-Host "An error occurred either during creation of new alerts or removal of old ones. See migration log for details." -ForegroundColor Red
                [AIOrgTelemetryHelper]::PublishEvent("AzSK Migration Error",@{ "StageName"= "Alert Setup"; "ErrorRecord" = ($_ | Out-String) }, $null)
                $MigrationOutput.AlertsMigration = "Failed. Message[$_]"
                $ErrorOccurred = $true;
                #eat the exception and continue with other migration
            }
            #endregion

            #region arm policies migration
            try
            {
                Write-Host ("Creating new policies and cleaning up olde ones...") -ForegroundColor Yellow;
                [MigrationHelper]::MigrateARMPolicies($subscriptionContext.SubscriptionId, $subscriptionContext.Scope, $InvocationContext);
                Write-Host ("Successfully completed creating new ARM policies.") -ForegroundColor Green;
                $MigrationOutput.ARMPoliciesMigration = "Success"
            }
            catch
            {
                Write-Host "An error occurred either during creation of new policies or removal of old ones. See migration log for details." -ForegroundColor Red
                [AIOrgTelemetryHelper]::PublishEvent("AzSK Migration Error",@{ "StageName"= "ARM Policy Setup"; "ErrorRecord" = ($_ | Out-String); "MigrationStatus"= ($MigrationOutput | Out-String) }, $null)
                $MigrationOutput.ARMPoliciesMigration = "Failed. Message[$_]"
                $ErrorOccurred = $true;
                #eat the exception and continue with other migration
            }
            #endregion

            #region attestation migration
            try
            {
                Write-Host ("Migrating the attestation data to new storage account...") -ForegroundColor Yellow;
                [MigrationHelper]::MigrateStorageToLatest()
                Write-Host ("Successfully completed migrating the attestation data.") -ForegroundColor Green;
                $MigrationOutput.StorageDataMigration = "Success"
            }
            catch
            {
                Write-Host "An error occurred either during migration of attestation data to new storage account. See migration log for details." -ForegroundColor Red
                [AIOrgTelemetryHelper]::PublishEvent("AzSK Migration Error",@{ "StageName"= "Attestation Migration"; "ErrorRecord" = ($_ | Out-String); "MigrationStatus"= ($MigrationOutput | Out-String) }, $null)
                $MigrationOutput.StorageDataMigration = "Failed. Message[$_]"
                $ErrorOccurred = $true;
                #eat the exception and continue with other migration
            }
            #endregion

            #region update security center policies
            try
            {
                Write-Host ("Updating Security Center policies as per latest configuration...") -ForegroundColor Yellow;
                [MigrationHelper]::UpdateASC($subscriptionContext.SubscriptionId)
                Write-Host ("Successfully updated Security Center policies.") -ForegroundColor Green;
                $MigrationOutput.ASCUpdate = "Success"
            }
            catch
            {
                Write-Host "An error occurred during updation of Security Center policies as per latest configuration. See migration log for details." -ForegroundColor Red
                [AIOrgTelemetryHelper]::PublishEvent("AzSK Migration Error",@{ "StageName"= "ASC Update"; "ErrorRecord" = ($_ | Out-String); "MigrationStatus"= ($MigrationOutput | Out-String) }, $null)
                $MigrationOutput.ASCUpdate = "Failed. Message[$_]"
                $ErrorOccurred = $true;
                #eat the exception and continue with other migration
            }
            #endregion

            #region CA migration
            try
            {
                if($migrateCA)
                {
                    Write-Host ("Installing CA using the latest module...") -ForegroundColor Yellow;
                    [MigrationHelper]::MigrateAutomationAccountToLatest($subscriptionContext.SubscriptionId, $InvocationContext, $vars, $AzureADAppName, $scanIntervalInHours)                    
                    Remove-AzureRmAutomationAccount -ResourceGroupName $([OldConstants]::AzSDKRGName) -Name $([OldConstants]::AutomationAccountName) -Force
                    [Helpers]::SetResourceGroupTags([OldConstants]::AzSDKRGName ,@{[OldConstants]::RunbookVersionTagName=""}, $true)
                    Write-Host ("Successfully completed re-configuring CA.") -ForegroundColor Green;
                }
                else
                {
                    $caresources = Find-AzureRmResource -ResourceNameEquals $([Constants]::AutomationAccountName)
                    if(($caresources | Measure-Object).Count -eq 0)
                    {                        
                        Write-Host ("The current subscription is not configured with CA.") -ForegroundColor Yellow;
                    }
                    else
                    {
                        Write-Host ("CA has been already migrated for this subscription.") -ForegroundColor Green;
                    }
                }
                $MigrationOutput.CAMigration = "Success"
            }
            catch
            {
                Write-Host "An error occurred either during CA migration. See migration log for details." -ForegroundColor Red
                [AIOrgTelemetryHelper]::PublishEvent("AzSK Migration Error",@{ "StageName"= "CA Setup"; "ErrorRecord" = ($_ | Out-String); "MigrationStatus"= ($MigrationOutput | Out-String) }, $null)
                $MigrationOutput.CAMigration = "Failed. Message[$_]"
                $ErrorOccurred = $true;
                #eat the exception and continue with other migration
            }
            #endregion

            #region cleanup of old CA SPN

            $subscriptionScope = "/subscriptions/{0}" -f $subscriptionContext.SubscriptionId

            $azskspnformatstring = "AzSDK_CA_SPN";
            $azskRoleAssignments = Get-AzureRmRoleAssignment -Scope $subscriptionScope -RoleDefinitionName Reader | Where-Object { $_.DisplayName -like "$($azskspnformatstring)*" }

            $azskRoleAssignments | ForEach-Object{
                $roleAssignment = $_
                #TODO Need to uncomment below code later
                #Remove-AzureRmRoleAssignment -ObjectId $roleAssignment.ObjectId -RoleDefinitionName "Reader"
                #Remove-AzureRmRoleAssignment -ObjectId $roleAssignment.ObjectId -RoleDefinitionName "Contributor"
            }

            #endregion

            #region to warn about other resources
            $resources = Find-AzureRmResource -ResourceGroupNameEquals $([OldConstants]::AzSDKRGName) | Where-Object { -not ($_.Name -like "$([OldConstants]::StorageAccountPreName)*")}
            #filterout our resources
            if(($resources | Measure-Object).Count -gt 0)
            {
                $resourceString = [Helpers]::ConvertToPson($resources);
                Write-Host "We found resources which are not owned by AzSK. You need to migrate them to appropriate resource groups." -ForegroundColor Yellow
                Write-Host $resourceString
                $MigrationOutput.ResourcesToBeMigrated = "Failed. $resourceString"
            }
            else
            {
                $MigrationOutput.ResourcesToBeMigrated = "Success"
            }
            #endregion

            #region complete migration
            $MigrationOutput.ErrorOccurred = $ErrorOccurred
            if($MigrationOutput.ErrorOccurred -eq $false)
            {
                [MigrationHelper]::CompleteMigration($subscriptionContext.SubscriptionId, $MigrationOutput)
                #endregion
                [AIOrgTelemetryHelper]::PublishEvent("AzSK Migration Completed",@{ "MigrationStatus"= ($MigrationOutput | Out-String) }, $null)    
                write-host ([Constants]::SingleDashLine + "`r`nMigration completed successfully`r`n"+[Constants]::SingleDashLine) -ForegroundColor Green
            }
            else
            {
                [MigrationHelper]::PersistMigrationOutput($subscriptionContext.SubscriptionId, $MigrationOutput)
                [AIOrgTelemetryHelper]::PublishEvent("AzSK Migration Not Completed",@{ "MigrationStatus"= ($MigrationOutput | Out-String) }, $null)    
                write-host ([Constants]::SingleDashLine + "`r`nAn error during migration, please retry again. If issue still continue please reach out to support team.`r`n"+[Constants]::SingleDashLine) -ForegroundColor Red
            }            
            
        }
        catch
        {
            $MigrationOutput.ErrorOccurred = $ErrorOccurred
            [AIOrgTelemetryHelper]::PublishEvent("AzSK Migration Error",@{ "StageName"= "Migration Block"; "ErrorRecord" = ($_ | Out-String); "MigrationStatus"= ($MigrationOutput | Out-String) }, $null)
            [MigrationHelper]::RollBackMigration($subscriptionContext.SubscriptionId, $MigrationOutput)
            throw "Error occurred during migration. $($_.Exception)"
        }
    }

    static [void] UpdateASC([string] $SubscriptionId)
    {
        $secCenter = [SecurityCenter]::new($SubscriptionId);
        if ($secCenter) 
        {
            #calling the ASC policy method with default params i.e. without ASC security poc email and phone number
            $secCenter.SetPolicies();
        } 
    }

    static [void] SetupAzSKResources([string] $subscriptionId, [string] $location)
    {        
        $RGName = [ConfigurationManager]::GetAzSKConfigData().AzSKRGName;
        $storageAccountName = ([Constants]::StorageAccountPreName + (Get-Date).ToUniversalTime().ToString("yyyyMMddHHmmss"))
        [MigrationHelper]::StorageAccountInstance = [StorageHelper]::new($subscriptionId, $RGName, $location, $storageAccountName);
        [MigrationHelper]::StorageAccountInstance.CreateStorageContainerIfNotExists([Constants]::AttestationDataContainerName)
        [MigrationHelper]::StorageAccountInstance.CreateStorageContainerIfNotExists([Constants]::CAScanOutputLogsContainerName)
        [MigrationHelper]::StorageAccountInstance.CreateStorageContainerIfNotExists([Constants]::CAScanProgressSnapshotsContainerName)        
    }
    static [void] RollBackMigration([string] $subscriptionId, [PSObject] $MigrationOutput)
    {
        try
        {
        #delete partially created resources
        [MigrationHelper]::PersistMigrationOutput($subscriptionId, $MigrationOutput);
        }
        catch
        {
            [AIOrgTelemetryHelper]::PublishEvent("AzSK Migration Error",@{ "StageName"= "Rollback"; "ErrorRecord" = ($_ | Out-String) }, $null)
        }
    }
    static [void] MigrateStorageToLatest()
    {
        $OldRgName = [OldConstants]::AzSDKRGName

        #region Step1: Migrate Storage
        $storageAccounts = @();
        $storageAccounts += Get-AzureRmStorageAccount -ResourceGroupName $OldRgName -ErrorAction SilentlyContinue;
        $storageAccounts = $storageAccounts | Where-Object { $_.StorageAccountName -like "$([OldConstants]::StorageAccountPreName)*" } ;
        if(($storageAccounts | Measure-Object).Count -ne 1)
        {
            return;
        }
        $context = $storageAccounts[0].Context;

        $newRGName = [ConfigurationManager]::GetAzSKConfigData().AzSKRGName;
        $newStorageAccounts = @();
        $newStorageAccounts  += Get-AzureRmStorageAccount -ResourceGroupName $newRGName -ErrorAction SilentlyContinue;
        $newStorageAccounts = $newStorageAccounts | Where-Object { $_.StorageAccountName -like "$([Constants]::StorageAccountPreName)*" } ;
        if(($newStorageAccounts | Measure-Object).Count -ne 1)
        {
            return;
        }
        $newContext = $newStorageAccounts[0].Context;

        #region Migrate Attestation Data
        $AzSKTemp = [Constants]::AzSKAppFolderPath + "\Migration\Attestation";                
        if(-not (Test-Path "$AzSKTemp"))
        {
            mkdir -Path "$AzSKTemp" -ErrorAction Stop | Out-Null
        }
        else
        {
            Remove-Item -Path "$AzSKTemp\*" -Force -Recurse 
        }

        $attestationBlobs = Get-AzureStorageBlob -Container $([OldConstants]::AttestationDataContainerName) -Context $context -ErrorAction SilentlyContinue
        if(($attestationBlobs | Measure-Object).Count -gt 0)
        {
            $attestationBlobs | ForEach-Object {
                $blob = $_;
                $filename = "$AzSKTemp\$($blob.Name)"
                Get-AzureStorageBlobContent -Blob $_.Name -Container $([OldConstants]::AttestationDataContainerName) -Destination $filename -Context $context -Force -ErrorAction SilentlyContinue
            }
        }

        #move the stuff to new storage account
        
        #region to check if there are existing blobs in the new attestation container
        $attestationBlobs = Get-AzureStorageBlob -Container $([Constants]::AttestationDataContainerName) -Context $newContext
        if(($attestationBlobs | Measure-Object).Count -gt 0)
        {
            Write-Host "Skipping migration of attestation data. Found attestation data in new container. Migrating again can corrupt your latest attestation data." -ForegroundColor Yellow
        }
        else
        {
            $controlStateArray = Get-ChildItem -Path "$AzSKTemp"                
            $controlStateArray | ForEach-Object {
                $state = $_;
                $loopValue = 3;
                while($loopValue -gt 0)
                {
                    $loopValue = $loopValue - 1;
                    try
                    {
                        Set-AzureStorageBlobContent -File $state.FullName -Container $([Constants]::AttestationDataContainerName) -BlobType Block -Context $newContext -Force -ErrorAction Stop
                        $loopValue = 0;
                    }
                    catch
                    {
                        #eat this exception and retry
                    }
                }
            }
        }
        #endregion

        #region Migrate Central Scanning Config Data
        $AzSKTemp = [Constants]::AzSKAppFolderPath + "\Migration\CentralScanConfig";                
        if(-not (Test-Path "$AzSKTemp"))
        {
            mkdir -Path "$AzSKTemp" -ErrorAction Stop | Out-Null
        }
        else
        {
            Remove-Item -Path "$AzSKTemp\*" -Force -Recurse 
        }

        $centalScanningConfiguration = Get-AzureStorageBlob -Container $([OldConstants]::CAMultiSubScanConfigContainerName) -Context $context -ErrorAction SilentlyContinue
        #if($null -eq $centalScanningConfiguration)
        #{
        # return;
        #}

        if(($centalScanningConfiguration | Measure-Object).Count -gt 0)
        {
            $centalScanningConfiguration | ForEach-Object {
                $blob = $_;
                $filename = "$AzSKTemp\$($blob.Name)"
                Get-AzureStorageBlobContent -Blob $_.Name -Container $([OldConstants]::CAMultiSubScanConfigContainerName) -Destination $filename -Context $context -Force -ErrorAction SilentlyContinue
            }
        }

        #move the stuff to new storage account

        $configDataFiles = Get-ChildItem -Path "$AzSKTemp"                
            $configDataFiles | ForEach-Object {
                $file = $_;
                $loopValue = 3;
                while($loopValue -gt 0)
                {
                    $loopValue = $loopValue - 1;
                    try
                    {
                        Set-AzureStorageBlobContent -File $file.FullName -Container $([Constants]::CAMultiSubScanConfigContainerName) -BlobType Block -Context $newContext -Force -ErrorAction Stop
                        $loopValue = 0;
                    }
                    catch
                    {
                        #eat this exception and retry
                    }
                }
            }


        #endregion

        #region add migration tag to old storage account
        $oldStorageResource = Get-AzureRmResource -ResourceId $storageAccounts[0].Id
        $resourceTags = $oldStorageResource.Tags
        if($null -eq $resourceTags)
        {
            $resourceTags = @{}
        }
        if($resourceTags.ContainsKey("Migration"))
        {
            $resourceTags["Migration"] = [DateTime]::UtcNow.ToString("yyyyMMdd_HHmmss");
        }
        else
        {
            $resourceTags.Add("Migration",[DateTime]::UtcNow.ToString("yyyyMMdd_HHmmss"));
        }
        Set-AzureRmResource -Tag  $resourceTags -ResourceId $storageAccounts[0].Id -Force
        #endregion
        #endregion
    }

    static [void] PersistMigrationOutput([string] $subscriptionId, [PSObject] $MigrationOutput)
    {
        if($null -ne $MigrationOutput)
        {
            $temp = ($env:temp + "\AzSKTemp\");
            $fileName =  "MigrationOutput_"+ (Get-Date).ToUniversalTime().ToString("yyyyMMddHHmmss")+ ".json"
            if(-not (Test-Path -Path $temp))
            {
                mkdir -Path $temp -Force
            }
            [Helpers]::ConvertToJsonCustom($MigrationOutput) | Out-File "$temp\$fileName" -Force;
            $oldStorageAccount = Find-AzureRmResource -ResourceNameContains $([OldConstants]::StorageAccountPreName) -ResourceGroupNameEquals $([OldConstants]::AzSDKRGName) -ResourceType 'Microsoft.Storage/storageAccounts'
            if($oldStorageAccount)
            {
                $storageHelper = [StorageHelper]::new($subscriptionId,[OldConstants]::AzSDKRGName,$oldStorageAccount.Location, $oldStorageAccount.Name);
                $fileInfos = @();
                $fileInfos += [System.IO.FileInfo]::new("$temp\$fileName");
                $storageHelper.UploadFilesToBlob("migration", "", $fileInfos, $true);
            }
            #Store logs to new storage
            try{
                $newStorageRGName = [ConfigurationManager]::GetAzSKConfigData().AzSKRGName
                $newStorageAccount = Find-AzureRmResource -ResourceNameContains $([Constants]::StorageAccountPreName) -ResourceGroupNameEquals $newStorageRGName -ResourceType 'Microsoft.Storage/storageAccounts'
                if($newStorageAccount)
                {
                    $storageHelper = [StorageHelper]::new($subscriptionId,$newStorageRGName,$newStorageAccount.Location, $newStorageAccount.Name);
                    $fileInfos = @();
                    $fileInfos += [System.IO.FileInfo]::new("$temp\$fileName");
                    $storageHelper.UploadFilesToBlob("migration", "", $fileInfos, $true);
                }
            }
            catch
            {
                #Kept blank to avoid issue with posting migration logs to new storage
            }
            

            #put a lock once the migration is started
            $azsdkRGScope = "/subscriptions/$subscriptionId/resourceGroups/$([OldConstants]::AzSDKRGName)"
            New-AzureRmResourceLock -LockName "AzSKMigrationLock" -LockLevel ReadOnly -Scope $azsdkRGScope -LockNotes "Migration lock by AzSK to avoid any future edits" -Force
        }
    }
    static [void] MigrateAutomationAccountToLatest([string] $subscriptionId, [PSObject] $invocationContext, [PSObject] $vars, [string] $AzureADAppName, [int] $scanIntervalInHours)
    {
        $azskRG = "*";
        $omsWSId = "";
        $omsWSKey = "";
        $altOMSWSId = "";
        $altOMSWSKey = "";
        $wUrl = "";
        $wHeaderName = "";
        $wHeaderValue = "";
        $disableAlertRunbook ="";
        $vars | ForEach-Object{
            if($_.Name -eq [Constants]::AppResourceGroupNames)
            {
                $azskRG = $_.Value
            }
            elseif($_.Name -eq [Constants]::OMSWorkspaceId)
            {
                $omsWSId = $_.Value
            }
            elseif($_.Name -eq [Constants]::OMSSharedKey)
            {
                $omsWSKey = $_.Value
            }
            elseif($_.Name -eq [Constants]::AltOMSWorkspaceId)
            {
                $altOMSWSId = $_.Value
            }
            elseif($_.Name -eq [Constants]::AltOMSSharedKey)
            {
                $altOMSWSKey = $_.Value
            }
            elseif($_.Name -eq [Constants]::WebhookUrl)
            {
                $wUrl = $_.Value
            }
            elseif($_.Name -eq [Constants]::WebhookAuthZHeaderName)
            {
                $wHeaderName = $_.Value
            }
            elseif($_.Name -eq [Constants]::WebhookAuthZHeaderValue)
            {
                $wHeaderValue = $_.Value
            }
            elseif($_.Name -eq [Constants]::DisableAlertRunbook)
            {
                $disableAlertRunbook = $_.Value
            }                        
        }        
        #TODO need to check the CA Scaling scenario

        $ccAccount = [CCAutomation]::new($subscriptionId, $invocationContext,`
                [ConfigurationManager]::GetAzSKConfigData().AzSKLocation, $azskRG,`
                $AzureADAppName, $scanIntervalInHours);
        #set the OMS settings
        $ccAccount.SetOMSSettings($omsWSId, $omsWSKey, $altOMSWSId, $altOMSWSKey);

        #set the Webhook settings
        $ccAccount.SetWebhookSettings($wUrl, $wHeaderName, $wHeaderValue);
        $ccAccount.InstallAzSKContinuousAssurance();

        #region to install the disable alertrunbook variable
        $RGName = [ConfigurationManager]::GetAzSKConfigData().AzSKRGName;
        if(-not [string]::IsNullOrWhiteSpace($disableAlertRunbook))
        {
            New-AzureRmAutomationVariable -Name $([Constants]::DisableAlertRunbook) -Value $disableAlertRunbook -Encrypted $false -ResourceGroupName $RGName -AutomationAccountName $([Constants]::AutomationAccountName) -ErrorAction Ignore
        }            
        [MigrationHelper]::SetCASPNPermissions($ccAccount);

        #endregion

    }
    static [void] MigrateAlerts([string] $subscriptionId, [PSObject] $invocationContext)
    {
        $mandatoryTags = [string]::Join(",", [ConfigurationManager]::GetAzSKConfigData().SubscriptionMandatoryTags);
        $alert = [Alerts]::new($subscriptionId, $invocationContext, $mandatoryTags);
        if ($alert) 
        {
            #calling alert method with default params i.e. without security contanct email and phone number
            $smsReceivers = $null;
            $emailReceivers = $null;
            $webhookUri = "";
            $curActionGroupResource = $alert.GetAlertActionGroup([OldConstants]::AzSDKRGName, [OldConstants]::AlertActionGroupName);
            if($curActionGroupResource)
            {
                $curActionGroupResourceData= Get-AzureRmResource -ResourceId $curActionGroupResource.ResourceId
                $emailReceivers = $curActionGroupResourceData.properties.emailReceivers
            }
            $curCriticalActionGroupResource = $alert.GetAlertActionGroup([OldConstants]::AzSDKRGName, [OldConstants]::CriticalAlertActionGroupName);
            if($curCriticalActionGroupResource)
            {
                $curCriticalActionGroupResourceData= Get-AzureRmResource -ResourceId $curCriticalActionGroupResource.ResourceId
                $smsReceivers = $curCriticalActionGroupResourceData.properties.smsReceivers
            }
            if($null -ne $emailReceivers)
            {
                $alert.SetAlerts($emailReceivers,$smsReceivers,$null);
                Find-AzureRmResource -ResourceGroupNameEquals $([OldConstants]::AzSDKRGName) -ResourceType "Microsoft.Insights/activityLogAlerts" -ErrorAction SilentlyContinue | Remove-AzureRmResource -Force -ErrorAction SilentlyContinue
                Find-AzureRmResource -ResourceGroupName $([OldConstants]::AzSDKRGName) -ResourceType "Microsoft.Insights/actiongroups" -ErrorAction SilentlyContinue | Remove-AzureRmResource -Force -ErrorAction SilentlyContinue                
                [Helpers]::SetResourceGroupTags([OldConstants]::AzSDKRGName ,@{[OldConstants]::AzSDKAlertsVersionTagName=""}, $true)
            }            
        }
        else{
            #No current alerts found
        }    
    }

    static [void] MigrateARMPolicies([string] $subscriptionId,[string] $scope, [PSObject] $invocationContext)
    {
        $mandatoryTags = [string]::Join(",", [ConfigurationManager]::GetAzSKConfigData().SubscriptionMandatoryTags);
        $armPolicy = [ARMPolicy]::new($subscriptionId, $invocationContext, $mandatoryTags);
        if ($armPolicy) 
        {
            #region AzSK TBR migration
            Write-Host "Checking for the presence of old policies..." -ForegroundColor Yellow
            $armPolicy.RemoveARMPolicies("AzSDK", $scope)            
            $armPolicy.RemoveARMPolicies("ISRM", $scope)

            #endregion

            $armPolicy.SetARMPolicies();
        }
    }

    static [void] CompleteMigration([string] $subscriptionId, [PSObject] $MigrationOutput)
    {
        #apply tag
        $tagName = [Constants]::MigrationTagName
        $resourceGroupTags = [Helpers]::GetResourceGroupTags([OldConstants]::AzSDKRGName)
        if($null -eq $resourceGroupTags)
        {
            $resourceTags = @{}
        }
        if($resourceGroupTags.ContainsKey($tagName))
        {
            $resourceGroupTags[$tagName] = [DateTime]::UtcNow.ToString("yyyyMMdd_HHmmss");
        }
        else
        {
            $resourceGroupTags.Add($tagName,[DateTime]::UtcNow.ToString("yyyyMMdd_HHmmss"));
        }
        $RGName = [ConfigurationManager]::GetAzSKConfigData().AzSKRGName;
        [Helpers]::SetResourceGroupTags($RGName,$resourceGroupTags,$false,$false)

        #set the tag on the storage account
        $resources = @();
        $resources += Find-AzureRmResource -ResourceNameContains $([Constants]::StorageAccountPreName) -ResourceGroupNameEquals $RGName -ResourceType "Microsoft.Storage/storageAccounts"
        if(($resources | Measure-Object).Count -gt 0)
        {
            [MigrationHelper]::SetMigrationTag($resources[0].ResourceId);
        }

        #set tag on automation account
        $resources = @();
        $resources += Find-AzureRmResource -ResourceNameEquals $([Constants]::AutomationAccountName) -ResourceGroupNameEquals $RGName -ResourceType "Microsoft.Automation/automationAccounts"
        if(($resources | Measure-Object).Count -gt 0)
        {
            [MigrationHelper]::SetMigrationTag($resources[0].ResourceId);                        
        }

        [MigrationHelper]::PersistMigrationOutput($subscriptionId, $MigrationOutput);            
    }

    static [void] SetMigrationTag([string] $ResourceId)
    {
        $tagName = [Constants]::MigrationTagName;
        $tagValue = [DateTime]::UtcNow.ToString("yyyyMMdd_HHmmss");
        $resourceTags = @{};
        $resourceTags.Add($tagName,$tagValue);
        [Helpers]::SetResourceTags($ResourceId, $resourceTags, $false, $true);
    }


    static [void] SetCASPNPermissions([CCAutomation] $ccAutomation)
    {
        $runAsConnection = $ccAutomation.GetRunAsConnection();
        if($runAsConnection)
        {
            $existingAppId = $runAsConnection.FieldDefinitionValues.ApplicationId                
            $ADApp = Get-AzureRmADApplication -ApplicationId $existingAppId -ErrorAction SilentlyContinue                
            if($ADApp)
            {
                #check SP permissions
                $haveRGAccess = $ccAutomation.CheckServicePrincipalRGAccess($existingAppId, [OldConstants]::AzSDKRGName, "Owner")
                #assign SP $ccAutomation
                if(!$haveRGAccess)
                {
                    $ccAutomation.SetServicePrincipalRGAccess($existingAppId, [OldConstants]::AzSDKRGName, "Owner")
                }
            }
        }
    }


}

[MigrationHelper]::StartMigration($SubscriptionContext, $InvocationContext, $AzureADAppName)