Mengonfigurasi lingkungan pengembangan untuk skrip penyebaran dalam templat ARM

Pelajari cara membuat lingkungan pengembangan untuk mengembangkan dan menguji skrip penyebaran templat ARM dengan gambar skrip penyebaran. Anda dapat membuat instans kontainer Azure atau menggunakan Docker. Kedua opsi tersebut dibahas dalam artikel ini.

Prasyarat

Kontainer Azure PowerShell

Jika Anda tidak memiliki skrip penerapan Azure PowerShell, Anda bisa membuat hello.ps1 dengan menggunakan konten berikut:

param([string] $name)
$output = 'Hello {0}' -f $name
Write-Output $output
$DeploymentScriptOutputs = @{}
$DeploymentScriptOutputs['text'] = $output

Kontainer Azure CLI

Untuk gambar kontainer Azure CLI, Anda bisa membuat file hello.sh dengan menggunakan konten berikut:

FIRSTNAME=$1
LASTNAME=$2
OUTPUT="{\"name\":{\"displayName\":\"$FIRSTNAME $LASTNAME\",\"firstName\":\"$FIRSTNAME\",\"lastName\":\"$LASTNAME\"}}"
echo -n "Hello "
echo $OUTPUT | jq -r '.name.displayName'

Catatan

Saat Anda menjalankan skrip penyebaran Azure CLI, variabel lingkungan yang disebut AZ_SCRIPTS_OUTPUT_PATH menyimpan lokasi file output skrip. Variabel lingkungan tidak tersedia dalam kontainer lingkungan pengembangan. Untuk informasi selengkapnya tentang bekerja dengan output Azure CLI, lihat Bekerja dengan output dari skrip CLI.

Menggunakan instans kontainer Azure PowerShell

Untuk menulis skrip di komputer, Anda perlu membuat akun penyimpanan dan memasang akun penyimpanan ke instans kontainer. Sehingga Anda dapat mengunggah skrip Anda ke akun penyimpanan dan menjalankan skrip pada instans kontainer.

Catatan

Akun penyimpanan yang Anda buat untuk menguji skrip Anda bukanlah akun penyimpanan yang sama dengan yang digunakan layanan skrip penyebaran untuk menjalankan skrip. Layanan skrip penyebaran membuat nama unik sebagai berbagi pada setiap eksekusi.

Membuat instans kontainer Azure PowerShell

Templat Azure Resource Manager (template ARM) berikut membuat instans kontainer dan berbagi, lalu memasang berbagi ke gambar kontainer.

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "projectName": {
      "type": "string",
      "metadata": {
        "description": "Specify a project name that is used for generating resource names."
      }
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]",
      "metadata": {
        "description": "Specify the resource location."
      }
    },
    "containerImage": {
      "type": "string",
      "defaultValue": "mcr.microsoft.com/azuredeploymentscripts-powershell:az9.7",
      "metadata": {
        "description": "Specify the container image."
      }
    },
    "mountPath": {
      "type": "string",
      "defaultValue": "/mnt/azscripts/azscriptinput",
      "metadata": {
        "description": "Specify the mount path."
      }
    }
  },
  "variables": {
    "storageAccountName": "[toLower(format('{0}store', parameters('projectName')))]",
    "fileShareName": "[format('{0}share', parameters('projectName'))]",
    "containerGroupName": "[format('{0}cg', parameters('projectName'))]",
    "containerName": "[format('{0}container', parameters('projectName'))]"
  },
  "resources": [
    {
      "type": "Microsoft.Storage/storageAccounts",
      "apiVersion": "2023-01-01",
      "name": "[variables('storageAccountName')]",
      "location": "[parameters('location')]",
      "sku": {
        "name": "Standard_LRS"
      },
      "kind": "StorageV2",
      "properties": {
        "accessTier": "Hot"
      }
    },
    {
      "type": "Microsoft.Storage/storageAccounts/fileServices/shares",
      "apiVersion": "2023-01-01",
      "name": "[format('{0}/default/{1}', variables('storageAccountName'), variables('fileShareName'))]",
      "dependsOn": [
        "[resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName'))]"
      ]
    },
    {
      "type": "Microsoft.ContainerInstance/containerGroups",
      "apiVersion": "2023-05-01",
      "name": "[variables('containerGroupName')]",
      "location": "[parameters('location')]",
      "properties": {
        "containers": [
          {
            "name": "[variables('containerName')]",
            "properties": {
              "image": "[parameters('containerImage')]",
              "resources": {
                "requests": {
                  "cpu": 1,
                  "memoryInGB": "[json('1.5')]"
                }
              },
              "ports": [
                {
                  "protocol": "TCP",
                  "port": 80
                }
              ],
              "volumeMounts": [
                {
                  "name": "filesharevolume",
                  "mountPath": "[parameters('mountPath')]"
                }
              ],
              "command": [
                "/bin/sh",
                "-c",
                "pwsh -c 'Start-Sleep -Seconds 1800'"
              ]
            }
          }
        ],
        "osType": "Linux",
        "volumes": [
          {
            "name": "filesharevolume",
            "azureFile": {
              "readOnly": false,
              "shareName": "[variables('fileShareName')]",
              "storageAccountName": "[variables('storageAccountName')]",
              "storageAccountKey": "[listKeys(resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName')), '2023-01-01').keys[0].value]"
            }
          }
        ]
      },
      "dependsOn": [
        "[resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName'))]"
      ]
    }
  ]
}

Nilai default untuk jalur pemasangan adalah /mnt/azscripts/azscriptinput. Ini adalah jalur dalam instans kontainer tempat instans dipasang ke berbagi.

Gambar kontainer default yang ditentukan dalam templat adalah mcr.microsoft.com/azuredeploymentscripts-powershell:az9.7. Lihat daftar semua versi Azure PowerShell yang didukung.

Templat menangguhkan instans kontainer setelah 1.800 detik. Anda memiliki 30 menit sebelum instans kontainer masuk ke keadaan dihentikan dan sesi berakhir.

Untuk menyebarkan templat:

$projectName = Read-Host -Prompt "Enter a project name that is used to generate resource names"
$location = Read-Host -Prompt "Enter the location (i.e. centralus)"
$templateFile = Read-Host -Prompt "Enter the template file path and file name"
$resourceGroupName = "${projectName}rg"

New-AzResourceGroup -Location $location -name $resourceGroupName
New-AzResourceGroupDeployment -resourceGroupName $resourceGroupName -TemplateFile $templatefile -projectName $projectName

Unggah skrip penyebaran

Unggah skrip penyebaran Anda ke akun penyimpanan. Berikut adalah contoh skrip PowerShell:

$projectName = Read-Host -Prompt "Enter the same project name that you used earlier"
$fileName = Read-Host -Prompt "Enter the deployment script file name with the path"

$resourceGroupName = "${projectName}rg"
$storageAccountName = "${projectName}store"
$fileShareName = "${projectName}share"

$context = (Get-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccountName).Context
Set-AzStorageFileContent -Context $context -ShareName $fileShareName -Source $fileName -Force

Anda juga dapat mengunggah file dengan menggunakan portal Microsoft Azure atau Azure CLI.

Menguji skrip penyebaran

  1. Di portal Microsoft Azure, buka grup sumber daya tempat Anda menggunakan instans kontainer dan akun penyimpanan.

  2. Buka grup kontainer. Nama grup kontainer default adalah nama proyek yang ditambahkan dengan cg. Instans kontainer dalam status Berjalan.

  3. Di menu sumber daya, pilih Kontainer. Nama instans kontainer adalah nama proyek yang ditambahkan dengan kontainer.

    Screenshot of the deployment script connect container instance option in the Azure portal.

  4. Pilih Sambungkan, lalu pilih Sambungkan. Jika Anda tidak dapat terhubung ke instans kontainer, mulai ulang grup kontainer dan coba lagi.

  5. Di panel konsol, jalankan perintah berikut:

    cd /mnt/azscripts/azscriptinput
    ls
    pwsh ./hello.ps1 "John Dole"
    

    Outputnya adalah Halo John Dole.

    Screenshot of the deployment script connect container instance test output displayed in the console.

Menggunakan instans kontainer Azure CLI

Untuk menulis skrip di komputer, Anda perlu membuat akun penyimpanan dan memasang akun penyimpanan ke instans kontainer. Sehingga Anda dapat mengunggah skrip Anda ke akun penyimpanan dan menjalankan skrip pada instans kontainer.

Catatan

Akun penyimpanan yang Anda buat untuk menguji skrip Anda bukanlah akun penyimpanan yang sama dengan yang digunakan layanan skrip penyebaran untuk menjalankan skrip. Layanan skrip penyebaran membuat nama unik sebagai berbagi pada setiap eksekusi.

Menggunakan instans kontainer Azure CLI

Templat ARM berikut membuat instans kontainer dan berbagi file, lalu memasang berbagi file ke gambar kontainer:

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "projectName": {
      "type": "string",
      "metadata": {
        "description": "Specify a project name that is used for generating resource names."
      }
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]",
      "metadata": {
        "description": "Specify the resource location."
      }
    },
    "containerImage": {
      "type": "string",
      "defaultValue": "mcr.microsoft.com/azure-cli:2.9.1",
      "metadata": {
        "description": "Specify the container image."
      }
    },
    "mountPath": {
      "type": "string",
      "defaultValue": "/mnt/azscripts/azscriptinput",
      "metadata": {
        "description": "Specify the mount path."
      }
    }
  },
  "variables": {
    "storageAccountName": "[toLower(format('{0}store', parameters('projectName')))]",
    "fileShareName": "[format('{0}share', parameters('projectName'))]",
    "containerGroupName": "[format('{0}cg', parameters('projectName'))]",
    "containerName": "[format('{0}container', parameters('projectName'))]"
  },
  "resources": [
    {
      "type": "Microsoft.Storage/storageAccounts",
      "apiVersion": "2022-09-01",
      "name": "[variables('storageAccountName')]",
      "location": "[parameters('location')]",
      "sku": {
        "name": "Standard_LRS"
      },
      "kind": "StorageV2",
      "properties": {
        "accessTier": "Hot"
      }
    },
    {
      "type": "Microsoft.Storage/storageAccounts/fileServices/shares",
      "apiVersion": "2022-09-01",
      "name": "[format('{0}/default/{1}', variables('storageAccountName'), variables('fileShareName'))]",
      "dependsOn": [
        "[resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName'))]"
      ]
    },
    {
      "type": "Microsoft.ContainerInstance/containerGroups",
      "apiVersion": "2023-05-01",
      "name": "[variables('containerGroupName')]",
      "location": "[parameters('location')]",
      "properties": {
        "containers": [
          {
            "name": "[variables('containerName')]",
            "properties": {
              "image": "[parameters('containerImage')]",
              "resources": {
                "requests": {
                  "cpu": 1,
                  "memoryInGB": "[json('1.5')]"
                }
              },
              "ports": [
                {
                  "protocol": "TCP",
                  "port": 80
                }
              ],
              "volumeMounts": [
                {
                  "name": "filesharevolume",
                  "mountPath": "[parameters('mountPath')]"
                }
              ],
              "command": [
                "/bin/bash",
                "-c",
                "echo hello; sleep 1800"
              ]
            }
          }
        ],
        "osType": "Linux",
        "volumes": [
          {
            "name": "filesharevolume",
            "azureFile": {
              "readOnly": false,
              "shareName": "[variables('fileShareName')]",
              "storageAccountName": "[variables('storageAccountName')]",
              "storageAccountKey": "[listKeys(resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName')), '2022-09-01').keys[0].value]"
            }
          }
        ]
      },
      "dependsOn": [
        "storageAccount"
      ]
    }
  ]
}

Nilai default untuk jalur pemasangan adalah /mnt/azscripts/azscriptinput. Ini adalah jalur dalam instans kontainer tempat instans dipasang ke berbagi.

Gambar kontainer default yang ditentukan dalam templat adalah mcr.microsoft.com/azure-cli:2.9.1. Lihat daftar versi Azure CLI yang didukung.

Penting

Skrip penyebaran menggunakan gambar CLI yang tersedia dari Microsoft Container Registry (MCR). Dibutuhkan sekitar satu bulan untuk mensertifikasi gambar CLI untuk skrip penyebaran. Jangan gunakan versi CLI yang dirilis dalam waktu 30 hari. Untuk menemukan tanggal rilis untuk gambar, lihat Catatan rilis Azure CLI. Jika Anda menggunakan versi yang tidak didukung, pesan kesalahan mencantumkan versi yang didukung.

Templat menangguhkan instans kontainer setelah 1.800 detik. Anda memiliki 30 menit sebelum instans kontainer masuk ke status terminal dan sesi berakhir.

Untuk menyebarkan templat:

$projectName = Read-Host -Prompt "Enter a project name that is used to generate resource names"
$location = Read-Host -Prompt "Enter the location (i.e. centralus)"
$templateFile = Read-Host -Prompt "Enter the template file path and file name"
$resourceGroupName = "${projectName}rg"

New-AzResourceGroup -Location $location -name $resourceGroupName
New-AzResourceGroupDeployment -resourceGroupName $resourceGroupName -TemplateFile $templatefile -projectName $projectName

Unggah skrip penyebaran

Unggah skrip penyebaran Anda ke akun penyimpanan. Berikut ini adalah contoh PowerShell:

$projectName = Read-Host -Prompt "Enter the same project name that you used earlier"
$fileName = Read-Host -Prompt "Enter the deployment script file name with the path"

$resourceGroupName = "${projectName}rg"
$storageAccountName = "${projectName}store"
$fileShareName = "${projectName}share"

$context = (Get-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccountName).Context
Set-AzStorageFileContent -Context $context -ShareName $fileShareName -Source $fileName -Force

Anda juga dapat mengunggah file dengan menggunakan portal Microsoft Azure atau Azure CLI.

Menguji skrip penyebaran

  1. Di portal Microsoft Azure, buka grup sumber daya tempat Anda menggunakan instans kontainer dan akun penyimpanan.

  2. Buka grup kontainer. Nama grup kontainer default adalah nama proyek yang ditambahkan dengan cg. Instans kontainer ditampilkan dalam status Berjalan.

  3. Di menu sumber daya, pilih Kontainer. Nama instans kontainer adalah nama proyek yang ditambahkan dengan kontainer.

    Screenshot of the deployment script connect container instance option in the Azure portal.

  4. Pilih Sambungkan, lalu pilih Sambungkan. Jika Anda tidak dapat terhubung ke instans kontainer, mulai ulang grup kontainer dan coba lagi.

  5. Di panel konsol, jalankan perintah berikut:

    cd /mnt/azscripts/azscriptinput
    ls
    ./hello.sh John Dole
    

    Outputnya adalah Halo John Dole.

    Screenshot of the deployment script container instance test output displayed in the console.

Menggunakan Docker

Anda dapat menggunakan gambar kontainer Docker yang telah dikonfigurasi sebelumnya sebagai lingkungan pengembangan skrip penyebaran Anda. Untuk memasang Docker, lihat Dapatkan Docker. Anda juga perlu mengonfigurasi berbagi untuk memasang direktori, yang berisi skrip penyebaran ke dalam kontainer Docker.

  1. Tarik gambar kontainer skrip penyebaran ke komputer lokal:

    docker pull mcr.microsoft.com/azuredeploymentscripts-powershell:az4.3
    

    Contoh tersebut menggunakan versi PowerShell 4.3.0.

    Untuk menarik gambar CLI dari MCR:

    docker pull mcr.microsoft.com/azure-cli:2.0.80
    

    Contoh ini menggunakan versi CLI 2.0.80. Skrip penerapan menggunakan gambar kontainer CLI default yang ditemukan di sini.

  2. Jalankan gambar Docker secara lokal.

    docker run -v <host drive letter>:/<host directory name>:/data -it mcr.microsoft.com/azuredeploymentscripts-powershell:az4.3
    

    Ganti <huruf kandar host> dan <nama direktori host> dengan folder yang ada di drive bersama. Ini memetakan folder ke folder /data dalam kontainer. Misalnya, untuk memetakan D:\docker:

    docker run -v d:/docker:/data -it mcr.microsoft.com/azuredeploymentscripts-powershell:az4.3
    

    -it berarti menjaga gambar kontainer tetap hidup.

    Contoh CLI:

    docker run -v d:/docker:/data -it mcr.microsoft.com/azure-cli:2.0.80
    
  3. Cuplikan layar berikut menunjukkan cara menjalankan skrip PowerShell, mengingat Anda memiliki file helloworld.ps1 di drive bersama.

    Screenshot of the Resource Manager template deployment script using Docker command.

Setelah skrip berhasil diuji, Anda dapat menggunakannya sebagai skrip penyebaran di templat Anda.

Langkah berikutnya

Dalam artikel ini, Anda telah mempelajari cara menggunakan skrip penyebaran. Untuk menelusuri tutorial skrip penyebaran: