Framework/Helpers/ResourceHelper.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
using namespace Microsoft.WindowsAzure.Storage.Blob
using namespace Microsoft.Azure.Commands.Management.Storage.Models
using namespace Microsoft.WindowsAzure.Commands.Common.Storage.ResourceModel
Set-StrictMode -Version Latest
class ResourceGroupHelper: AzSKRoot
{
    [string] $ResourceGroupName;
    [string] $ResourceGroupLocation = "EastUS2";

    [PSObject] $ResourceGroup;

    ResourceGroupHelper([string] $subscriptionId, [string] $resourceGroupName):
        Base($subscriptionId)
    {
        $this.CreateInstance($resourceGroupName, "EastUS2");
    }

    ResourceGroupHelper([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceGroupLocation):
        Base($subscriptionId)
    {
        $this.CreateInstance($resourceGroupName, $resourceGroupLocation);
    }

    hidden [void] CreateInstance([string] $resourceGroupName, [string] $resourceGroupLocation)
    {
        if([string]::IsNullOrWhiteSpace($resourceGroupName))
        {
            throw [System.ArgumentException] ("The argument 'resourceGroupName' is null or empty");
        }
        $this.ResourceGroupName = $resourceGroupName;
        if(-not [string]::IsNullOrWhiteSpace($resourceGroupLocation))
        {
            $this.ResourceGroupLocation = $resourceGroupLocation;
        }
    }

    [void] CreateResourceGroupIfNotExists()
    {
        if(-not $this.ResourceGroup)
        {
            $rg = Get-AzureRmResourceGroup -Name $this.ResourceGroupName -ErrorAction ignore
            #$rg = Get-AzureRmResourceGroup | Where-Object { $_.ResourceGroupName -eq $this.ResourceGroupName } | Select-Object -First 1
            if(-not $rg)
            {
                $this.PublishCustomMessage("Creating resource group [$($this.ResourceGroupName)]...");
                $result = [Helpers]::NewAzSKResourceGroup($this.ResourceGroupName, $this.ResourceGroupLocation, "");
                if($result)
                {
                    $this.ResourceGroup = $result;
                    $this.PublishCustomMessage("Successfully created resource group [$($this.ResourceGroupName)]", [MessageType]::Update);
                }
                else
                {
                    throw ([SuppressedException]::new("Error occured while creating resource group [$($this.ResourceGroupName)]", [SuppressedExceptionType]::Generic))                
                }
            }
            else
            {
                $this.ResourceGroup = $rg;
            }
        }
    }
}

class StorageHelper: ResourceGroupHelper
{
    hidden [PSStorageAccount] $StorageAccount = $null;
    [string] $StorageAccountName;

    hidden [string] $ResourceType = "Microsoft.Storage/storageAccounts";

    StorageHelper([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceGroupLocation, [string] $storageAccountName):
        Base($subscriptionId, $resourceGroupName, $resourceGroupLocation)
    {
        if([string]::IsNullOrWhiteSpace($storageAccountName))
        {
            throw [System.ArgumentException] ("The argument 'storageAccountName' is null or empty");
        }
        $this.StorageAccountName = $storageAccountName;
    }

    [void] CreateStorageIfNotExists()
    {
        if(-not $this.StorageAccount)
        {
            $this.CreateResourceGroupIfNotExists();

            $existingResources = Find-AzureRmResource -ResourceGroupNameEquals $this.ResourceGroupName -ResourceType $this.ResourceType

            # Assuming 1 storage account is needed on Resource group
            if(($existingResources | Measure-Object).Count -gt 1)
            {
                throw ([SuppressedException]::new(("Multiple storage accounts found in resource group: [$($this.ResourceGroupName)]. This is not expected. Please contact support team."), [SuppressedExceptionType]::InvalidOperation))
            }
            elseif(($existingResources | Measure-Object).Count -eq 0)
            {
                $this.PublishCustomMessage("Creating a storage account: ["+ $this.StorageAccountName +"]...");
                $newStorage = [Helpers]::NewAzskCompliantStorage($this.StorageAccountName, $this.ResourceGroupName, $this.ResourceGroupLocation);
                if($newStorage)
                {
                    $this.PublishCustomMessage("Successfully created storage account [$($this.StorageAccountName)]", [MessageType]::Update);
                }
                else
                {
                    throw ([SuppressedException]::new("Failed to create storage account [$($this.StorageAccountName)]", [SuppressedExceptionType]::Generic))
                }
            }
            elseif(($existingResources | Measure-Object).Count -eq 1)
            {
                $this.StorageAccountName = $existingResources.Name;
            }

            # Fetch the Storage account context
            $this.StorageAccount = Get-AzureRmStorageAccount -ResourceGroupName $this.ResourceGroupName -Name $this.StorageAccountName -ErrorAction Ignore
            if(-not ($this.StorageAccount -and $this.StorageAccount.Context))
            {
                $this.StorageAccount = $null;
                throw ([SuppressedException]::new("Unable to fetch the storage account [$($this.StorageAccountName)]", [SuppressedExceptionType]::InvalidOperation))                
            }
        }
    }

    [AzureStorageContainer] CreateStorageContainerIfNotExists([string] $containerName)
    {
        return $this.CreateStorageContainerIfNotExists($containerName, [BlobContainerPublicAccessType]::Off);
    }

    [AzureStorageContainer] CreateStorageContainerIfNotExists([string] $containerName, [BlobContainerPublicAccessType] $accessType)
    {
        if([string]::IsNullOrWhiteSpace($containerName))
        {
            throw [System.ArgumentException] ("The argument 'containerName' is null or empty");
        }

        $this.CreateStorageIfNotExists();

        $container = Get-AzureStorageContainer -Context $this.StorageAccount.Context -Name $containerName -ErrorAction Ignore
        if(($container| Measure-Object).Count -eq 0)
        {
            $this.PublishCustomMessage("Creating storage container [$containerName]...");
            $container = New-AzureStorageContainer -Context $this.StorageAccount.Context -Name $containerName -Permission $accessType
            if($container)
            {
                $this.PublishCustomMessage("Successfully created storage container [$containerName]", [MessageType]::Update);
            }
        }

        if(($container| Measure-Object).Count -eq 0)
        {
            throw ([SuppressedException]::new("Unable to fetch/create the container [$containerName] under storage account [$($this.StorageAccountName)]", [SuppressedExceptionType]::InvalidOperation))                
        }

        return $container;
    }

    [AzureStorageContainer] UploadFilesToBlob([string] $containerName, [string] $blobPath, [System.IO.FileInfo[]] $filesToUpload, [bool] $overwrite)
    {
        return $this.UploadFilesToBlob([string] $containerName, [BlobContainerPublicAccessType]::Off, $blobPath, $filesToUpload, $overwrite);
    }

    [AzureStorageContainer] UploadFilesToBlob([string] $containerName, [string] $blobPath, [System.IO.FileInfo[]] $filesToUpload)
    {
        return $this.UploadFilesToBlob([string] $containerName, [BlobContainerPublicAccessType]::Off, $blobPath, $filesToUpload);
    }

    [AzureStorageContainer] UploadFilesToBlob([string] $containerName, [BlobContainerPublicAccessType] $accessType, [string] $blobPath, [System.IO.FileInfo[]] $filesToUpload)
    {
        return $this.UploadFilesToBlob([string] $containerName, $accessType, $blobPath, $filesToUpload, $true);
    }

    [AzureStorageContainer] UploadFilesToBlob([string] $containerName, [BlobContainerPublicAccessType] $accessType, [string] $blobPath, [System.IO.FileInfo[]] $filesToUpload, [bool] $overwrite)
    {
        $result = $null;
        if($filesToUpload -and $filesToUpload.Count -ne 0)
        {
            $result = $this.CreateStorageContainerIfNotExists($containerName, $accessType);

            $this.PublishCustomMessage("Uploading [$($filesToUpload.Count)] file(s) to container [$containerName]...");
            $filesToUpload |
            ForEach-Object {
                $blobName = $_.Name;
                if(-not [string]::IsNullOrWhiteSpace($blobPath))
                {
                    $blobName = $blobPath + "/" + $blobName;
                }

                if($overwrite)
                {
                    [Helpers]::RemoveUtf8BOM($_);
                    Set-AzureStorageBlobContent -Blob $blobName -Container $containerName -File $_.FullName -Context $this.StorageAccount.Context -Force | Out-Null
                }
                else
                {
                    $currentBlob = Get-AzureStorageBlob -Blob $blobName -Container $containerName -Context $this.StorageAccount.Context -ErrorAction Ignore
                
                    if(-not $currentBlob)
                    {
                        [Helpers]::RemoveUtf8BOM($_);
                        Set-AzureStorageBlobContent -Blob $blobName -Container $containerName -File $_.FullName -Context $this.StorageAccount.Context | Out-Null
                    }
                }

            };
            $this.PublishCustomMessage("All files have been uploaded to container [$containerName]");
        }
        else
        {
            throw [System.ArgumentException] ("The argument 'filesToUpload' is null or empty");
        }
        return $result;
    }

    [string] GenerateSASToken([string] $containerName)
    {
        $this.CreateStorageContainerIfNotExists($containerName);
        $sasToken = New-AzureStorageContainerSASToken -Name $containerName -Context $this.StorageAccount.Context -ExpiryTime (Get-Date).AddMonths(6) -Permission rl -Protocol HttpsOnly -StartTime (Get-Date).AddDays(-1)
        if([string]::IsNullOrWhiteSpace($sasToken))
        {
            throw ([SuppressedException]::new("Unable to create SAS token for storage account [$($this.StorageAccountName)]", [SuppressedExceptionType]::InvalidOperation))
        }
        return $sasToken;
    }
}

class AppInsightHelper: ResourceGroupHelper
{
    [PSObject] $AppInsightInstance = $null;
    [string] $AppInsightName;
    [string] $AppInsightLocation;

    hidden [string] $ResourceType = "Microsoft.Insights/components";

    AppInsightHelper([string] $subscriptionId, [string] $resourceGroupName, [string] $resourceGroupLocation, [string] $appInsightName):
        Base($subscriptionId, $resourceGroupName, $resourceGroupLocation)
    {
        if([string]::IsNullOrWhiteSpace($appInsightName))
        {
            throw [System.ArgumentException] ("The argument 'appInsightName' is null or empty");
        }
        $this.AppInsightName = $appInsightName;
        $this.AppInsightLocation = "East US";
    }

    [void] CreateAppInsightIfNotExists()
    {
        if(-not $this.AppInsightInstance)
        {
            $this.CreateResourceGroupIfNotExists();

            $existingResources = Find-AzureRmResource -ResourceGroupNameEquals $this.ResourceGroupName -ResourceType $this.ResourceType

            # Assuming 1 storage account is needed on Resource group
            if(($existingResources | Measure-Object).Count -gt 1)
            {
                throw ([SuppressedException]::new(("Multiple application insight resources found in resource group: [$($this.ResourceGroupName)]. This is not expected. Please contact support team."), [SuppressedExceptionType]::InvalidOperation))
            }
            elseif(($existingResources | Measure-Object).Count -eq 0)
            {
                $this.PublishCustomMessage("Creating an application insight resource: ["+ $this.AppInsightName +"]...");
                $newResource = New-AzureRmResource -ResourceName $this.AppInsightName -ResourceGroupName $this.ResourceGroupName -ResourceType $this.ResourceType `
                                    -Location $this.AppInsightLocation -PropertyObject @{"Application_Type"="web"} -Force
                if($newResource)
                {
                    $this.PublishCustomMessage("Successfully created application insight resource [$($this.AppInsightName)]", [MessageType]::Update);
                }
                else
                {
                    throw ([SuppressedException]::new("Failed to create application insight resource [$($this.AppInsightName)]", [SuppressedExceptionType]::Generic))
                }
            }
            elseif(($existingResources | Measure-Object).Count -eq 1)
            {
                $this.AppInsightName = $existingResources.Name;
            }

            # Fetch the application insight
            $this.AppInsightInstance = Find-AzureRmResource -ResourceNameEquals $this.AppInsightName -ResourceGroupName $this.ResourceGroupName -ResourceType $this.ResourceType -ExpandProperties 
            if(-not ($this.AppInsightInstance -and $this.AppInsightInstance.Properties))
            {
                $this.AppInsightInstance = $null;
                throw ([SuppressedException]::new("Unable to fetch application insight resource [$($this.AppInsightName)]", [SuppressedExceptionType]::InvalidOperation))                
            }
        }
    }
}