Azure Automationで、SQL DatabaseのSELECT結果をAzure BLOB Storageに定期的に格納します。
Automationアカウント作成 / Runbook作成 / Runbookスケジュール設定
- 以下の記事を参照下さい。
Azure AutomationでSQL DatabaseのSELECT件数をメール(Slack)通知する
Storage格納用Runbook作成
- Runbook編集画面で以下のコードを貼り付けます。workflow名はRunbookの名称と合わせるようにして下さい。
workflow kwhr-test-blob
{
param(
[parameter(Mandatory=$True)]
[string] $SqlServer,
[parameter(Mandatory=$False)]
[int] $SqlServerPort = 1433,
[parameter(Mandatory=$True)]
[string] $Database,
[parameter(Mandatory=$True)]
[string] $Table,
[parameter(Mandatory=$True)]
[PSCredential] $SqlCredName,
[parameter(Mandatory=$True)]
[string] $resourceGroup,
[parameter(Mandatory=$True)]
[string] $storageAccountName,
[parameter(Mandatory=$True)]
[string] $ContainerName,
[parameter(Mandatory=$True)]
[string] $BlobName
)
$LocalTargetDirectory = "C:\"
$Conn = Get-AutomationConnection -Name AzureRunAsConnection
$Null = Add-AzureRMAccount -ServicePrincipal -Tenant $Conn.TenantID -ApplicationID $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint
$Null = Set-AzureRmCurrentStorageAccount -ResourceGroupName $resourceGroup -StorageAccountName $storageAccountName
# Get the username and password from the SQL Credential
$SqlUsername = $SqlCredName.UserName
$SqlPass = $SqlCredName.GetNetworkCredential().Password
inlinescript {
$Date = Get-Date -Format "yyyy-MMdd-HHmmss"
$DateBlobName = $Date + "_" + $using:BlobName
$LocalFile = $using:LocalTargetDirectory + $DateBlobName
# Define the connection to the SQL Database
$Conn = New-Object System.Data.SqlClient.SqlConnection("Server=tcp:$using:SqlServer,$using:SqlServerPort;Database=$using:Database;User ID=$using:SqlUsername;Password=$using:SqlPass;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;")
# Open the SQL connection
$Conn.Open()
# Define the SQL command to run. In this case we are getting the number of rows in the table
$Cmd=new-object system.Data.SqlClient.SqlCommand("SELECT * from dbo.$using:Table", $Conn)
$Cmd.CommandTimeout=120
# Execute the SQL command
$Ds=New-Object system.Data.DataSet
$Da=New-Object system.Data.SqlClient.SqlDataAdapter($Cmd)
[void]$Da.fill($Ds)
$table = $Ds.Tables[0]
$table | Export-Csv $Localfile
# Upload file to the Blob Storage
Set-AzureStorageBlobContent -File $LocalFile -Container $using:ContainerName -Blob $blobname
# List of Blob Storage
Write-Output "StorageAccountName:$using:storageAccountName, ContainerName:$using:ContainerName, Blob List"
Get-AzureStorageBlob -Container $using:ContainerName
# Close the SQL connection
$Conn.Close()
}
}
- 入力したら[保存]を選択し、[テストウィンドウ]を選択する。
- パラメータ入力画面を以下の内容で入力します。
- SQLSERVER : SQL Databaseサーバー名
- SQLSERVERPORT : 1433
- DATABASE : データベース名
- TABLE : テーブル名
- SQLCREDNAME : SQL Databaseの資格情報名を入力する
- RESOURCEGROUP : アップロード先ストレージアカウントのリソースグループ名
- STORAGEACCOUNTNAME : アップロード先ストレージアカウント名
- CONTAINERNAME : アップロード先コンテナ名
- BLOBNAME : アップロードするファイル名(ファイル名はYYYY-MMdd-HHmmss_$BLOBNAMEとなります)
- Storageにファイルがアップロードされていたら成功
以上