sitecore-azure.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
#
# sitecore_azure.ps1
#

function Get-DefaultCredentialStore()
{
return Join-Path $env:USERPROFILE -ChildPath 'azure.csv'
}

<#.Synopsis
Use this function to unattendant login to Azure acount.
 
.DESCRIPTION
This function will store credentials to Azure account in encrypted file. Next credantials are used to silent login to Azure account.
Note: If this function is used for a first time then you will be prompted for credentials.
 
.EXAMPLE
 Login-AzureAccountSilent
 Login to Azure account with a default settings - credentials will be stored in file $env:USERPROFILE\azure.csv
 
.EXAMPLE
 Login-AzureAccountSilent -KeyName 'MyPrivateAzureAccount' -CredentialsPath 'C:\MyFavoriteFolder\azurelogin.csv'
 
.NOTE
  
#>

function Login-AzureAccountSilent
{
    [CmdletBinding()]
    param
    (
        # KeyName - Name of the key under which the credentials will be stored
        [Parameter()]
        $KeyName = 'AzureLogin',
# CredentialsPath - Path to the credentials store file
[parameter()]
        [string]$CredentialsPath = (Get-DefaultCredentialStore)      
)

Write-Verbose "Import credentials from $CredentialsPath"
Import-CredentialStore -Path $CredentialsPath 

if( -not (Test-StoredCredential -Key $KeyName) )
{
Write-Verbose "Credentials with key $KeyName not exist in $CredentialsPath"

New-StoredCredential -Key $KeyName -Message "Please enter credentials to Azure account"

Export-CredentialStore -Path $CredentialsPath
}


if( (Get-AzureRmContext).Account -eq $null )
{
Login-AzureRmAccount -Credential (Get-StoredPSCredential -Key $KeyName) | Out-Null
}
else
{
Write-Verbose "Already login to Azure account $($azAccout.Id)"
}
}


<#
.Synopsis
 Checks if all resources required to deploy Sitecore on Azure are supported in Location region
 
.DESCRIPTION
 Checks if all resources required to deploy Sitecore on Azure are supported in Location region
 
.EXAMPLE
 Test-SitecoreAzureRegion -Location 'West Europe'
 
#>

function Test-SitecoreAzureRegion
{ 
    [CmdletBinding()]
    Param
    (
        # Location name of Azure region
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        $Location
    )

    $resources = @(
        "Microsoft.Cache/Redis";
        "microsoft.insights/alertrules";
        "Microsoft.Insights/components";
        "Microsoft.Search/searchServices";
        "Microsoft.Sql/servers"
        "Microsoft.Sql/servers/databases";
        "Microsoft.Web/serverFarms";
        "Microsoft.Web/sites"
    )

    $unsupportedResources = $false

    foreach( $resource in $resources )
    {
        $splited = $resource -split "/",2

        $isSupported = ((Get-AzureRmResourceProvider -ProviderNamespace $($splited[0])).ResourceTypes | Where-Object ResourceTypeName -eq $($splited[1])).Locations.Contains($location)

        if( $isSupported -eq $false )
        {
            $unsupportedResources = $true
            Write-Verbose "Unsupported resource '$resource' in '$location'"
        }
    }

    if( $unsupportedResources -eq $true )
    {
        Write-Warning "Please check 'https://kb.sitecore.net/articles/617478'"
    }

    return -not $unsupportedResources
}


<#
.Synopsis
   Copy local files to existing Azure container
.DESCRIPTION
   This function can be used to copy local files to existing Azure container.
   Files that already exist in the container will not be copied.
   Please use -Force switch to overwrite existing files.
.EXAMPLE
   $files = Get-ChildItem "C:\AzureArmFiles" -Directory | Get-ChildItem -Recurse -Filter "*.json"
   Copy-FilesToAzureStorage -Files $files -ContainerName "arm" -AzureStorageContext $storageAccount.Context -PathToRemove "C:\AzureArmFiles"
 
#>

function Copy-FilesToAzureContainer
{
    [CmdletBinding()]
    Param
    (
        # Files an array of local files to copy to Azure container
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true)]
        $Files,
        [string]
        $ContainerName,
# AzureStorageContext can be by Get-AzureRmStorageAccount
        [System.Object]
        $AzureStorageContext,
        # PathToRemove part of local path to remove from files name
[string]
        $PathToRemove,
# Use Force to overwrite existig files.
        [switch]
        $Force = $false
    ) 

    $containerContent = Get-AzureStorageBlob -Context $AzureStorageContext -Container $ContainerName  -ErrorAction Stop

    foreach($file in $Files)
    {
        $localFile = $file.FullName
        $blobFile = $file.FullName.Replace($PathToRemove, "")
            
        Write-Verbose "$localFile will be copied to container:'$ContainerName' ,blob:'$blobFile'"

        if ($Force) 
        {
            $blobInfo = Set-AzureStorageBlobContent -File $localFile -Container $ContainerName -Blob $blobFile -Context $AzureStorageContext -Force
        } 
        else
        {

            $blobExists =  $containerContent | Where-Object { ($_.Name -replace '/','\' ) -eq $blobFile }
            if( $blobExists ) 
            { 
                Write-Verbose "The $blobFile already exists in container '$ContainerName'" 
                continue
            }
             
            $blobInfo = Set-AzureStorageBlobContent -File $localFile -Container $ContainerName -Blob $blobFile -Context $AzureStorageContext
        }    
    }
}


<#
.Synopsis
   Get-AzureStorageBlobText returns blob content as text and can be stored as variable
.DESCRIPTION
   This is alternative for Get-AzureStorageBlobContent, this function downlads blob content to local file.
   Sometime we just want to get file content and store as variable, we don't want to download file.
.EXAMPLE
   $license = Get-AzureStorageBlobText -ContainerName $armContainer -BlobName "license.xml" -AzureStorageContext $account.Context
#>

function Get-AzureStorageBlobText
{
    [CmdletBinding()]
    Param
    (
        # Param1 help description
        [Parameter(Mandatory=$true)]
        [string] $BlobName,
        [Parameter(Mandatory=$true)]
        [string] $ContainerName,
        [Parameter(Mandatory=$true)]
        [System.Object] $AzureStorageContext
    ) 

    $blob = Get-AzureStorageBlob -Context $AzureStorageContext -Container $ContainerName -Blob $BlobName

    return $blob.ICloudBlob.DownloadText()
}

<#
.Synopsis
   Write to host array of parameters from passed JSON object $deployParemeters = @{ parameter1 = ""; parameter2="";} }
.DESCRIPTION
    
.EXAMPLE
    
#>

function Out-AzureDeployParameters
{
    [CmdletBinding()]
    Param
    (
        # Json object
        [Parameter()]
        [System.Object] $Json
    )

    $properties = $Json | Get-Member -MemberType NoteProperty 

    $properties.Name | ForEach-Object -Process { Write-Host "`t$_ = """";" } -Begin { Write-Host "`$deployParemeters = @{" } -End { Write-Host "}" }

}


<#
.Synopsis
   Gets Azure deploy parameters from local azuredeploy.parameters.json and return JSON object.
.DESCRIPTION
    
.EXAMPLE
    
#>

function Get-LocalDeployParametersToJson
{
    [CmdletBinding()]
    Param
    (
        # Path to 'azuredeploy.parameters.json' file
        [Parameter()]
        [string] $ParametersFile
    )

    $paramJson = Get-Content $ParametersFile -Raw | ConvertFrom-Json

    if ($paramJson."`$schema") {
        $paramJson = $paramJson.parameters
    }

    return $paramJson
}

<#
.Synopsis
   Gets Azure deploy parameters from blob azuredeploy.parameters.json stored in Azure container and return JSON object.
.DESCRIPTION
    
.EXAMPLE
    
#>

function Get-BlobDeployParametersToJson
{
    [CmdletBinding()]
    Param
    (
        # Param1 help description
        [Parameter(Mandatory=$true)]
        [string] $BlobName,
        [Parameter(Mandatory=$true)]
        [string] $ContainerName,
        [Parameter(Mandatory=$true)]
        [System.Object] $AzureStorageContext
    )

    $paramJson1 = (Get-AzureStorageBlobText -ContainerName $ContainerName -BlobName $BlobName -AzureStorageContext $AzureStorageContext )

    $paramJson = $paramJson1.Substring(1) | ConvertFrom-Json

    if ($paramJson."`$schema") {
        $paramJson = $paramJson.parameters
    }

    return $paramJson
}

Export-ModuleMember -Function Test-SitecoreAzureRegion
Export-ModuleMember -Function Login-AzureAccountSilent
Export-ModuleMember -Function Copy-FilesToAzureContainer
Export-ModuleMember -Function Get-AzureStorageBlobText
Export-ModuleMember -Function Out-AzureDeployParameters
Export-ModuleMember -Function Get-LocalDeployParametersToJson
Export-ModuleMember -Function Get-BlobDeployParametersToJson