Last active
February 25, 2020 16:18
-
-
Save ivanbuzyka/70db190d540e34300dab5015f21d00bf to your computer and use it in GitHub Desktop.
Azure automation PowerShell runbook for maintenance of Sitecore databases
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Getting values of automation variables | |
$resourceGroupName = Get-AutomationVariable -Name 'ResourceGroupName' | |
$sqlServerName = Get-AutomationVariable -Name 'SqlServerName' | |
$keyVaultName = Get-AutomationVariable -Name 'KeyVaultName' | |
$kvSqlAdminUserNameKey = Get-AutomationVariable -Name 'kvSqlAdminUserNameKey' | |
$kvSqlAdminPasswordKey = Get-AutomationVariable -Name 'kvSqlAdminPasswordKey' | |
$AzureSQLServerFQDN = $sqlServerName + ".database.windows.net" | |
$connection = Get-AutomationConnection -Name 'AzureRunAsConnection' | |
# Login to Azure context using service principal | |
Connect-AzAccount -ServicePrincipal -CertificateThumbprint $connection.CertificateThumbprint -ApplicationId $connection.ApplicationID -Tenant $connection.TenantID | |
$sqlAdminUserName = (Get-AzKeyVaultSecret -VaultName $keyVaultName -Name $kvSqlAdminUserNameKey).SecretValueText | |
$sqlAdminPassword = (Get-AzKeyVaultSecret -VaultName $keyVaultName -Name $kvSqlAdminPasswordKey).SecretValueText | |
# Get all databases within resource group and SQL server | |
$databases = Get-AzSqlDatabase -ResourceGroupName $resourceGroupName -ServerName $sqlServerName | |
foreach($db in $databases) | |
{ | |
if($db.DatabaseName -eq "master") | |
{ | |
# do not do a maintenance of system master DB | |
continue | |
} | |
Write-Output "Starting maintenance of "$db.DatabaseName | |
$SQLOutput = $(Invoke-Sqlcmd -ServerInstance $AzureSQLServerFQDN -Username $sqlAdminUserName -Password $sqlAdminPassword -Database $db.DatabaseName -Query "exec [dbo].[AzureSQLMaintenance] @Operation='all' ,@LogToTable=1" -QueryTimeout 65535 -ConnectionTimeout 60 -Verbose) 4>&1 | |
Write-Output "################# SQL CMD Output #################" | |
Write-Output $SQLOutput | |
Write-Output "##################################################" | |
Write-Output "Finished maintenance of "$db.DatabaseName | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment