sitecore-azure.ps1

#
# 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