Skrip PowerShell - ubah data di cloud menggunakan Azure Data Factory
Skrip PowerShell ini membuat alur yang mentransformasi data di cloud dengan menjalankan program Spark pada kluster Azure HDInsight Spark.
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
- Akun Azure Storage. Buat skrip Python dan file input, dan unggah ke penyimpanan Azure. Output dari program Spark disimpan di akun penyimpanan ini. Kluster Spark sesuai permintaan menggunakan akun penyimpanan yang sama dengan penyimpanan utamanya.
Unggah skrip Python ke akun Blob Storage Anda
Buat file Python bernama WordCount_Spark.py dengan konten berikut:
import sys from operator import add from pyspark.sql import SparkSession def main(): spark = SparkSession\ .builder\ .appName("PythonWordCount")\ .getOrCreate() lines = spark.read.text("wasbs://adftutorial@<storageaccountname>.blob.core.windows.net/spark/inputfiles/minecraftstory.txt").rdd.map(lambda r: r[0]) counts = lines.flatMap(lambda x: x.split(' ')) \ .map(lambda x: (x, 1)) \ .reduceByKey(add) counts.saveAsTextFile("wasbs://adftutorial@<storageaccountname>.blob.core.windows.net/spark/outputfiles/wordcount") spark.stop() if __name__ == "__main__": main()Ganti <storageAccountName> dengan nama akun Azure Storage Anda. Kemudian, simpan file tersebut.
Di Azure Blob Storage Anda, buat kontainer bernama adftutorial jika tidak ada.
Buat folder bernama spark.
Buat subfolder bernama script di dalam folder spark.
Unggah file WordCount_Spark.py ke subfolder skrip.
Unggah file input
- Buat file bernama minecraftstory.txt dengan beberapa teks. Program spark menghitung jumlah kata dalam teks ini.
- Buat subfolder bernama
inputfilesdalam foldersparkkontainer blob. - Unggah
minecraftstory.txtke subfolderinputfiles.
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:\.
powershell Set-ExecutionPolicy Unrestricted -Scope CurrentUser
# Set variables with your own values
$resourceGroupName = "<Azure resource group name>"
$dataFactoryName = "<Data factory name. Must be globally unique.>"
$dataFactoryRegion = "East US"
$storageAccountName = "<Az.Storage account name> "
$storageAccountKey = "<Az.Storage account key>"
$subscriptionID = "<Azure subscription ID>"
$tenantID = "<tenant ID>"
$servicePrincipalID = "<Active directory service principal ID>"
$servicePrincipalKey = "<Active directory service principal key>"
$pipelineName = "SparkTransformPipeline"
# Create a resource group
New-AzResourceGroup -Name $resourceGroupName -Location $dataFactoryRegion
# Create a data factory
$df = Set-AzDataFactory -ResourceGroupName $resourceGroupName -Location $dataFactoryRegion -Name $dataFactoryName
# Create an Az.Storage linked service in the data factory
## JSON definition of the linked service.
$storageLinkedServiceDefinition = @"
{
"name": "AzureStorageLinkedService",
"properties": {
"type": "AzureStorage",
"typeProperties": {
"connectionString": {
"value": "DefaultEndpointsProtocol=https;AccountName=$storageAccountName;AccountKey=$storageAccountKey",
"type": "SecureString"
}
}
}
}
"@
## IMPORTANT: store the JSON definition in a file that will be used by the Set-AzDataFactoryLinkedService command.
$storageLinkedServiceDefinition | Out-File c:\AzureStorageLinkedService.json
## Creates an Az.Storage linked service
Set-AzDataFactoryLinkedService -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName -Name "AzureStorageLinkedService" -File c:\AzureStorageLinkedService.json
# Create on-demand Spark linked service in the data factory
## JSON definition of the linked service.
$sparkLinkedServiceDefinition = @"
{
"name": "OnDemandSparkLinkedService",
"properties": {
"type": "HDInsightOnDemand",
"typeProperties": {
"clusterSize": 2,
"clusterType": "spark",
"timeToLive": "00:15:00",
"hostSubscriptionId": "$subscriptionID",
"servicePrincipalId": "$servicePrincipalID",
"servicePrincipalKey": {
"value": "$servicePrincipalKey",
"type": "SecureString"
},
"tenant": "$tenantID",
"clusterResourceGroup": "$resourceGroupName",
"version": "3.6",
"osType": "Linux",
"clusterNamePrefix":"ADFSparkSample",
"linkedServiceName": {
"referenceName": "AzureStorageLinkedService",
"type": "LinkedServiceReference"
}
}
}
}
"@
## IMPORTANT: store the JSON definition in a file that will be used by the Set-AzDataFactoryLinkedService command.
$sparkLinkedServiceDefinition | Out-File c:\OnDemandSparkLinkedService.json
# Creates an on-demand Spark linked service
Set-AzDataFactoryLinkedService -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName -Name "OnDemandSparkLinkedService" -File "C:\OnDemandSparkLinkedService.json"
# Create a pipeline in the data factory
## JSON definition of the pipeline
$pipelineDefinition = @"
{
"name": "SparkTransformPipeline",
"properties": {
"activities": [
{
"name": "MySparkActivity",
"type": "HDInsightSpark",
"linkedServiceName": {
"referenceName": "OnDemandSparkLinkedService",
"type": "LinkedServiceReference"
},
"typeProperties": {
"rootPath": "adftutorial/spark",
"entryFilePath": "script/WordCount_Spark.py",
"getDebugInfo": "Failure",
"sparkJobLinkedService": {
"referenceName": "AzureStorageLinkedService",
"type": "LinkedServiceReference"
}
}
}
]
}
}
"@
## IMPORTANT: store the JSON definition in a file that will be used by the Set-AzDataFactoryPipeline command.
$pipelineDefinition | Out-File c:\SparkTransformPipeline.json
## Create a pipeline with Spark Activity in the data factory
Set-AzDataFactoryPipeline -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName -Name "SparkTransformPipeline" -File "c:\SparkTransformPipeline.json"
# Create a pipeline run
## JSON definition for dummy pipeline parameters
$pipelineParameters = @"
{
"dummy": "b"
}
"@
## IMPORTANT: store the JSON definition in a file that will be used by the Invoke-AzDataFactoryPipeline command.
$pipelineParameters | Out-File c:\PipelineParameters.json
# Create a pipeline run by using parameters
$runId = Invoke-AzDataFactoryPipeline -DataFactoryName $dataFactoryName -ResourceGroupName $resourceGroupName -PipelineName $pipelineName -ParameterFile c:\PipelineParameters.json
# Check the pipeline run status until it finishes
Start-Sleep -Seconds 30
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 300
}
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(-30) `
-RunStartedBefore (Get-Date).AddMinutes(30) `
-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. |
| Set-AzDataFactoryV2LinkedService | Buat layanan tertaut di pabrik data. Layanan tertaut menautkan penyimpanan data atau komputasi ke pabrik data. |
| Set-AzDataFactoryV2Pipeline | Membuat alur di pabrik data. Alur memuat satu atau beberapa aktivitas yang melakukan operasi tertentu. Dalam alur ini, aktivitas spark mengubah data dengan menjalankan program pada kluster Azure HDInsight Spark. |
| 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.