Menggunakan PowerShell untuk membuat alur pabrik data untuk menyalin data dari SQL Server ke Azure
Contoh skrip PowerShell ini membuat alur di Azure Data Factory yang menyalin data dari database SQL Server ke Azure Blob Storage.
Catatan
Artikel ini menggunakan modul Azure Az PowerShell, yang merupakan modul PowerShell yang direkomendasikan untuk berinteraksi dengan Azure. Untuk mulai menggunakan modul Az PowerShell, lihat Menginstal Azure PowerShell. Untuk mempelajari cara bermigrasi ke modul Az PowerShell, lihat Memigrasikan Azure PowerShell dari AzureRM ke Az.
Sampel ini memerlukan Azure PowerShell. Jalankan Get-Module -ListAvailable Az untuk menemukan versinya.
Jika Anda perlu menginstal atau meningkatkan, lihat Menginstal modul Azure PowerShell.
Jalankan cmdlet Connect-AzAccount untuk tersambung ke Azure.
Prasyarat
- SQL Server. Anda menggunakan database SQL Server sebagai penyimpanan data sumber dalam sampel ini.
- Akun Azure Storage. Anda menggunakan penyimpanan blob Azure sebagai penyimpanan data tujuan/sink dalam sampel ini. jika Anda tidak memiliki akun penyimpanan Azure, lihat artikel Membuat akun penyimpanan untuk langkah-langkah membuatnya.
- Rutime integrasi yang dihost sendiri. Unduh file MSI dari pusat unduhan dan jalankan untuk menginstal runtime integrasi yang dihost sendiri di mesin Anda.
Membuat sampel database di SQL Server
Dalam database SQL Server, buat tabel bernama emp menggunakan skrip SQL berikut:
CREATE TABLE dbo.emp ( ID int IDENTITY(1,1) NOT NULL, FirstName varchar(50), LastName varchar(50), CONSTRAINT PK_emp PRIMARY KEY (ID) ) GOSisipkan beberapa sampel ke dalam tabel:
INSERT INTO emp VALUES ('John', 'Doe') INSERT INTO emp VALUES ('Jane', 'Doe')
Skrip sampel
Penting
Skrip ini membuat file JSON yang menentukan entitas Azure Data Factory (layanan tertaut, himpunan data, dan alur) pada hard drive Anda di folder c:\.
$resourceGroupName = "<Resource group name>"
$dataFactoryName = "<Data factory name>" # must be globally unique
$storageAccountName = "<Az.Storage account name>"
$storageAccountKey = "<Az.Storage account key>"
$sqlServerName = "<SQL server name>"
$sqlDatabaseName = "SQL Server database name"
$sqlTableName = "emp" # create the emp table if it does not already exist in your database with ID, FirstName, and LastName columns of type String.
$sqlUserName = "<SQL Authentication - user name>"
$sqlPassword = "<SQL Authentication - user password>"
$blobFolderPath = "<Azure blob container name>/<Azure blob folder name>"
$integrationRuntimeName = "<Self-hosted integration runtime name"
$pipelineName = "SqlServerToBlobPipeline"
$dataFactoryRegion = "East US"
# Create a resource group
New-AzResourceGroup -Name $resourceGroupName -Location $dataFactoryRegion
# create a data factory
$df = Set-AzDataFactory -ResourceGroupName $resourceGroupName -Name $dataFactoryName -Location $dataFactoryRegion
# create a self-hosted integration runtime
Set-AzDataFactoryIntegrationRuntime -Name $integrationRuntimeName -Type SelfHosted -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName
# get the authorization key from the created integration runtime in the cloud
Get-AzDataFactoryIntegrationRuntimeKey -Name $integrationRuntimeName -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName | ConvertTo-Json
# IMPORTANT: Install self-hosted integration runtime on your machine and use one of the keys to register the IR installed on your machine with the cloud service
# create an Az.Storage linked service
## JSON definition of the linked service.
$storageLinkedServiceDefinition = @"
{
"name": "AzureStorageLinkedService",
"properties": {
"type": "AzureStorage",
"typeProperties": {
"connectionString": {
"value": "DefaultEndpointsProtocol=https;AccountName=$storageAccountName;AccountKey=$storageAccountKey",
"type": "SecureString"
}
}
}
}
"@
## IMPORTANT: stores the JSON definition in a file that will be used by the Set-AzDataFactoryLinkedService command.
$storageLinkedServiceDefinition | Out-File c:\AzureStorageLinkedService.json
## Creates a linked service in the data factory
Set-AzDataFactoryLinkedService -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName -Name "AzureStorageLinkedService" -File c:\AzureStorageLinkedService.json
# create an on-premises SQL Server linked service
## JSON definition of the linked service.
$sqlServerLinkedServiceDefinition = @"
{
"properties": {
"type": "SqlServer",
"typeProperties": {
"connectionString": {
"type": "SecureString",
"value": "Server=$sqlServerName;Database=$sqlDatabaseName;User ID=$sqlUserName;Password=$sqlPassword;Timeout=60"
}
},
"connectVia": {
"type": "integrationRuntimeReference",
"referenceName": "$integrationRuntimeName"
}
},
"name": "SqlServerLinkedService"
}
"@
## IMPORTANT: stores the JSON definition in a file that will be used by the Set-AzDataFactoryLinkedService command.
$sqlServerLinkedServiceDefinition | Out-File c:\SqlServerLinkedService.json
## Encrypt SQL Server credentials
New-AzDataFactoryLinkedServiceEncryptCredential -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName -IntegrationRuntimeName $integrationRuntimeName -File "c:\SqlServerLinkedService.json" > c:\EncryptedSqlServerLinkedService.json
# Create a SQL Server linked service
Set-AzDataFactoryLinkedService -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName "EncryptedSqlServerLinkedService" -File "c:\EncryptedSqlServerLinkedService.json"
# Create a source dataset for source SQL Server Database
## JSON definition of the dataset
$sourceSqlServerDatasetDefiniton = @"
{
"properties": {
"type": "SqlServerTable",
"typeProperties": {
"tableName": "$sqlTableName"
},
"structure": [
{
"name": "ID",
"type": "String"
},
{
"name": "FirstName",
"type": "String"
},
{
"name": "LastName",
"type": "String"
}
],
"linkedServiceName": {
"referenceName": "EncryptedSqlServerLinkedService",
"type": "LinkedServiceReference"
}
},
"name": "SqlServerDataset"
}
"@
## IMPORTANT: store the JSON definition in a file that will be used by the Set-AzDataFactoryDataset command.
$sourceSqlServerDatasetDefiniton | Out-File c:\SqlServerDataset.json
# Create an Azure Blob dataset in the data factory
Set-AzDataFactoryDataset -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName -Name "SqlServerDataset" -File "c:\SqlServerDataset.json"
# Create a dataset for sink Azure Blob Storage
## JSON definition of the dataset
$sinkBlobDatasetDefiniton = @"
{
"properties": {
"type": "AzureBlob",
"typeProperties": {
"folderPath": "$blobFolderPath",
"format": {
"type": "TextFormat"
}
},
"linkedServiceName": {
"referenceName": "AzureStorageLinkedService",
"type": "LinkedServiceReference"
}
},
"name": "AzureBlobDataset"
}
"@
## IMPORTANT: store the JSON definition in a file that will be used by the Set-AzDataFactoryDataset command.
$sinkBlobDatasetDefiniton | Out-File c:\AzureBlobDataset.json
## Create the Azure Blob dataset
Set-AzDataFactoryDataset -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName -Name "AzureBlobDataset" -File "c:\AzureBlobDataset.json"
# Create a pipeline in the data factory
## JSON definition of the pipeline
$pipelineDefinition = @"
{
"name": "$pipelineName",
"properties": {
"activities": [
{
"type": "Copy",
"typeProperties": {
"source": {
"type": "SqlSource"
},
"sink": {
"type":"BlobSink"
}
},
"name": "CopySqlServerToAzureBlobActivity",
"inputs": [
{
"referenceName": "SqlServerDataset",
"type": "DatasetReference"
}
],
"outputs": [
{
"referenceName": "AzureBlobDataset",
"type": "DatasetReference"
}
]
}
]
}
}
"@
## IMPORTANT: store the JSON definition in a file that will be used by the Set-AzDataFactoryPipeline command.
$pipelineDefinition | Out-File c:\SqlServerToBlobPipeline.json
## Create a pipeline in the data factory
Set-AzDataFactoryPipeline -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName -Name "$pipelineName" -File "c:\SqlServerToBlobPipeline.json"
# start the pipeline run
$runId = Invoke-AzDataFactoryPipeline -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName -PipelineName $pipelineName
# Check the pipeline run status until it finishes the copy operation
while ($True) {
$result = Get-AzDataFactoryActivityRun -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName -PipelineRunId $runId -RunStartedAfter (Get-Date).AddMinutes(-30) -RunStartedBefore (Get-Date).AddMinutes(30)
if (($result | Where-Object { $_.Status -eq "InProgress" } | Measure-Object).count -ne 0) {
Write-Host "Pipeline run status: In Progress" -foregroundcolor "Yellow"
Start-Sleep -Seconds 30
}
else {
Write-Host "Pipeline $pipelineName run finished. Result:" -foregroundcolor "Yellow"
$result
break
}
}
# Get the activity run details
$result = Get-AzDataFactoryActivityRun -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName `
-PipelineRunId $runId `
-RunStartedAfter (Get-Date).AddMinutes(-10) `
-RunStartedBefore (Get-Date).AddMinutes(10) `
-ErrorAction Stop
$result
if ($result.Status -eq "Succeeded") {`
$result.Output -join "`r`n"`
}`
else {`
$result.Error -join "`r`n"`
}
# To remove the data factory from the resource gorup
# Remove-AzDataFactory -Name $dataFactoryName -ResourceGroupName $resourceGroupName
#
# To remove the whole resource group
# Remove-AzResourceGroup -Name $resourceGroupName
Membersihkan penyebaran
Setelah menjalankan sampel skrip, Anda dapat menggunakan perintah berikut untuk menghapus grup sumber daya dan semua sumber daya yang terkait:
Remove-AzResourceGroup -ResourceGroupName $resourceGroupName
Untuk menghapus pabrik data dari grup sumber daya, jalankan perintah berikut:
Remove-AzDataFactoryV2 -Name $dataFactoryName -ResourceGroupName $resourceGroupName
Penjelasan skrip
Skrip ini menggunakan perintah berikut:
| Perintah | Catatan |
|---|---|
| Baru-AzResourceGroup | Membuat grup sumber daya tempat semua sumber daya disimpan. |
| Set-AzDataFactoryV2 | Membuat pabrik data. |
| New-AzDataFactoryV2LinkedServiceEncryptCredential | Mengenkripsi kredensial dalam layanan tertaut dan membuat definisi layanan tertaut baru dengan kredensial terenkripsi. |
| Set-AzDataFactoryV2LinkedService | Buat layanan tertaut di pabrik data. Layanan tertaut menautkan penyimpanan data atau komputasi ke pabrik data. |
| Set-AzDataFactoryV2Dataset | Membuat himpunan data di pabrik data. Himpunan data yang mewakili input/output untuk aktivitas dalam alur. |
| Set-AzDataFactoryV2Pipeline | Membuat alur di pabrik data. Alur memuat satu atau beberapa aktivitas yang melakukan operasi tertentu. Dalam alur ini, aktivitas salin menyalin data dari satu lokasi ke lokasi lain dalam Microsoft Azure Blob Storage. |
| Invoke-AzDataFactoryV2Pipeline | Membuat eksekusi untuk alur. Dengan kata lain, menjalankan alur. |
| Get-AzDataFactoryV2ActivityRun | Mendapatkan detail tentang jalannya aktivitas (eksekusi aktivitas) di alur. |
| Remove-AzResourceGroup | Menghapus grup sumber daya termasuk semua sumber daya berlapis. |
Langkah berikutnya
Untuk informasi selengkapnya tentang Azure PowerShell, lihat dokumentasi Azure PowerShell.
Sampel skrip PowerShell Azure Data Factory tambahan dapat ditemukan di Contoh PowerShell Azure Data Factory.