使用客制化脚本扩展自动化 SQL Server VM 设定

Azure VM客制化脚本扩展(Custom Script Extension)将让您可以从存储器帐户下载PowerShell脚本并执行之,透过这样一个简单的功能,您可以因应各种不同的VM客制化情境,弹性地自动化VM设定。在本篇文章中我们将带您了解如何从 Azure VM Image Gallery 中使用客制化脚本扩展来客制一个 SQL Server 2014 VM,我们将使用 SQL Powershell 脚本来启用 SQL Server Managed Backup 到 Microsoft Azure,这将让您可以备份您的 SQL Server 2014数据库到Azure Blob存储器服务上。

SQL Server 设定脚本

请参阅以下程序代码,您只需要将 [your Azure storage account][your Azure storage account key] 改为您 Azure 存储器的帐户及凭证即可,并另存此脚本为 CustomScriptSQLPS.ps1

 
 #import SQL Server powershell module 
import-module  sqlps -DisableNameChecking
 
#global variables - replace storage account name and key
$credentialName = "AzureStorageCredential_"+(RANDOM)
$storageAccountName = "[your Azure storage account]"
$storageAccountKey = "[your Azure storage account key]"
 
#start SQL Agent Service           
write-host "Starting SQL Server Agent service ..."
Start-Service  sqlserveragent -verbose

CD SQLSERVER:SQL\$env:COMPUTERNAME\DEFAULT

write-host "Creating SQL credential ..."
$secureString = convertto-securestring $storageAccountKey  -asplaintext -force    

#Create Credential
New-SqlCredential –name $credentialName –Identity $storageAccountName –secret $secureString 

$encryptionOption = New-SqlBackupEncryptionOption -NoEncryption

write-host "Enabling Managed SQL Server Backup..."

get-sqlsmartadmin | set-sqlsmartadmin -BackupEnabled $True 
-BackupRetentionPeriodInDays 7 -SqlCredential $credentialName -EncryptionOption 
$encryptionOption

write-host "Managed SQL Server backup current configuration:"
get-sqlsmartadmin | fl 

但是,我们无法直接提交此脚本,因客制化脚本扩展是使用 NTAUTHORITY\SYSTEM 帐户来执行脚本,所以我们必须建立另个脚本,来扮演管理员帐户角色,才能执行上面这段脚本。

 

利用另个认证来执行脚本

首先我们建立另个脚本取名作 start.ps1,内容如下。为了方便解说,我在下方加了 Line Number。

 1: $password =  ConvertTo-SecureString "[your admin account user password]" -AsPlainText -Force
 2: $credential = New-Object System.Management.Automation.PSCredential("$env:COMPUTERNAME\[your admin account]", $password)
 3: $command = $file = $PSScriptRoot + "\CustomScriptSQLPS.ps1"
 4: Enable-PSRemoting –force
 5: Invoke-Command -FilePath $command -Credential $credential -ComputerName $env:COMPUTERNAME
 6: Disable-PSRemoting -Force

Line 1:将管理员密码从 Plain text 转换到 Secured string,当然将密码直接放置于脚本中不是一个好的做法,这我们稍后再回来谈。

Line 2:建立执行主要脚本的认证,您可以使用和预备用来建立 VM 相同的帐户。

Line 3:指定主要脚本的确切路径。

Line 4 & 6:要在一个仿造的认证中执行主要脚本,我们必须启用 Windows Remote Management (WinRM),也就是 Line 4,而 Line 6 是关闭。

Line 5:使用 Invoke-Command cmdlet 来执行主要脚本 (会需要认证参数)。

 

使用客制化脚本扩展

现在我们已经准备好提交以上两个脚本至客制化脚本扩展,将两个脚本上传至您存储器帐户下的脚本容器中,接下来在您的工作站上边可执行以下脚本。

 1: $servicename = "[cloud service that hosts the VM]"
 2: $vmname = "[name of the VM]"
 3: $vm = Get-AzureVM -ServiceName $servicename -Name $vmname
 4: Set-AzureVMCustomScriptExtension -ContainerName scripts -StorageAccountName '[your storage account name]' -VM $vm -FileName 'start.ps1', 'CustomScriptSQLPS.ps1' -Run 'start.ps1' | Update-AzureVM -Verbose
 5: $status = Get-AzureVM -ServiceName $servicename -Name $vmname
 6: $result = $status.ResourceExtensionStatusList.ExtensionSettingStatus.SubStatusList | Select Name, @{"Label"="Message";Expression = {$_.FormattedMessage.Message }} 
 7: $result |fl
  

最重要的是第4行,它确保了于VM上安装客制化脚本扩展,并下载 start.ps1CustomScriptSQLPS.ps1,接着执行 start.ps1

于外部档案中读取密码

我们都知道应避免于程序代码中写入密码,所以现在要介绍的是加解密服务,我们将假设您已经利用 private key 于目标 VM 部署了凭证,且利用相同凭证的 public key 来加密到 password.txt 档案 (base-64 格式)。

 $cert = Get-ChildItem Cert:\LocalMachine\My\[certificate thumbprint]
 $bytes = [Text.Encoding]::UTF8.GetBytes("abcdefg")
 $encrypted = $cert.PublicKey.Key.Encrypt($bytes, $true)
 $base64 = [Convert]::ToBase64String($encrypted)
 Set-Content .\password.txt $base64

若您对于VM凭证管理还不太了解,可以参考 这里 (提供教学影片及命令提示字符下载)。

修改 start.ps1 并将以下程序代码复制取代原本的第一行:

 $cert = Get-ChildItem Cert:\LocalMachine\My\[certificate thumbprint]
 $base64 = Get-Content .\password.txt
 $encrypted = [Convert]::FromBase64String($base64)
 $bytes = $cert.PrivateKey.Decrypt($encrypted,$true)
 $password = [Text.Encoding]::UTF8.GetString($bytes) 

最后,于档案列表增加文件名来确认password.txt档案已传送至客制化脚本扩展。

  Set-AzureVMCustomScriptExtension -ContainerName scripts -StorageAccountName '[your storage account 
name]' -VM $vm -FileName 'start.ps1', 'CustomScriptSQLPS.ps1', 
'password.txt' -Run 'start.ps1' | Update-AzureVM -Verbose