Otomasyon PowerShell runbook'unda Azure Resource Manager şablonu dağıtma

Azure Resource Manager şablonu kullanarak bir Azure kaynağı dağıtan bir Otomasyon PowerShell runbook'u yazabilirsiniz. Şablonlar, Azure kaynaklarınızın dağıtımını otomatikleştirmek için Azure Otomasyonu kullanmanıza olanak sağlar. Resource Manager şablonlarınızı Azure Depolama gibi merkezi ve güvenli bir konumda tutabilirsiniz.

Bu makalede, yeni bir Azure Depolama hesabı dağıtmak için Azure Depolama'de depolanan Resource Manager şablonunu kullanan bir PowerShell runbook'u oluşturacağız.

Azure aboneliğiniz yoksa başlamadan önce ücretsiz bir hesap oluşturun.

Ön koşullar

  • En az bir kullanıcı tarafından atanan yönetilen kimliğe sahip bir Azure Otomasyonu hesabı. Daha fazla bilgi için bkz. Azure Otomasyonu hesabı için kullanıcı tarafından atanan yönetilen kimliği kullanma.

  • Az modülleri: Az.Accounts, Az.ManagedServiceIdentity, Az.Resourcesve Az.Storage. Otomasyon hesabına aktarılır. Daha fazla bilgi için bkz. Az modüllerini içe aktarma.

  • Kaynak Yöneticisi şablonunun depolanacağı Azure Depolama hesabı.

  • Azure PowerShell yerel bir makineye yüklenir. Azure PowerShell alma hakkında bilgi için bkz. Azure PowerShell Modülünü Yükleme. Az.ManagedServiceIdentity modülü de gerekir. Az.ManagedServiceIdentity bir önizleme modülüdür ve Az modülünün bir parçası olarak yüklenmez. Yüklemek için komutunu çalıştırın Install-Module -Name Az.ManagedServiceIdentity

Yönetilen kimliklere izin atama

Runbook'taki depolamayla ilgili görevleri gerçekleştirmek için yönetilen kimliklere izinler atayın.

  1. Bağlan-AzAccount cmdlet'ini kullanarak Azure'da etkileşimli olarak oturum açın ve yönergeleri izleyin.

    # Sign in to your Azure subscription
    $sub = Get-AzSubscription -ErrorAction SilentlyContinue
    if(-not($sub))
    {
        Connect-AzAccount
    }
    
    # If you have multiple subscriptions, set the one to use
    # Select-AzSubscription -SubscriptionId <SUBSCRIPTIONID>
    
  2. Aşağıdaki değişkenler için uygun bir değer sağlayın ve betiği yürütür.

    $resourceGroup = "resourceGroup"
    $automationAccount = "automationAccount"
    $storageAccount = "storageAccount"
    $userAssignedManagedIdentity = "userAssignedManagedIdentity"
    $storageTemplate = "path\storageTemplate.json"
    $runbookScript = "path\runbookScript.ps1"
    
  3. cmdlet'ini Get-AzUserAssignedIdentityyürütmek için rolü reader sistem tarafından atanan yönetilen kimliğe atayın.

    $SAMI = (Get-AzAutomationAccount -ResourceGroupName $resourceGroup -Name $automationAccount).Identity.PrincipalId
    New-AzRoleAssignment `
        -ObjectId $SAMI `
        -ResourceGroupName $resourceGroup `
        -RoleDefinitionName "Reader"
    
  4. Depolama hesabına yönelik eylemler için rolü Storage Account Contributor kullanıcı tarafından atanan yönetilen kimliğe atayın.

    $UAMI_ID = (Get-AzUserAssignedIdentity -ResourceGroupName $resourceGroup -Name $userAssignedManagedIdentity).PrincipalId
    New-AzRoleAssignment `
        -ObjectId $UAMI_ID `
        -ResourceGroupName $resourceGroup `
        -RoleDefinitionName "Storage Account Contributor"
    

Resource Manager şablonu oluşturma

Bu örnekte, yeni bir Azure Depolama hesabı dağıtan bir Resource Manager şablonu kullanırsınız. adlı storageTemplate.json yerel bir dosya oluşturun ve aşağıdaki kodu yapıştırın:

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "storageAccountType": {
      "type": "string",
      "defaultValue": "Standard_LRS",
      "allowedValues": [
        "Standard_LRS",
        "Standard_GRS",
        "Standard_ZRS",
        "Premium_LRS"
      ],
      "metadata": {
        "description": "Storage Account type"
      }
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]",
      "metadata": {
        "description": "Location for all resources."
      }
    }
  },
  "variables": {
    "storageAccountName": "[concat(uniquestring(resourceGroup().id), 'standardsa')]"
  },
  "resources": [
    {
      "type": "Microsoft.Storage/storageAccounts",
      "name": "[variables('storageAccountName')]",
      "apiVersion": "2018-02-01",
      "location": "[parameters('location')]",
      "sku": {
          "name": "[parameters('storageAccountType')]"
      },
      "kind": "Storage", 
      "properties": {
      }
    }
  ],
  "outputs": {
      "storageAccountName": {
          "type": "string",
          "value": "[variables('storageAccountName')]"
      }
  }
}

Resource Manager şablonunu Azure Dosyalar’a kaydedin

Azure dosya paylaşımı oluşturmak ve karşıya yüklemek storageTemplate.jsoniçin PowerShell'i kullanın. Azure portalında dosya paylaşımı oluşturma ve karşıya dosya yükleme yönergeleri için bkz. Windows'da Azure Dosyalar kullanmaya başlama.

Bir dosya paylaşımı oluşturmak ve Resource Manager şablonunu bu dosya paylaşımına yüklemek için aşağıdaki komutları çalıştırın.

# Get the access key for your storage account
$key = Get-AzStorageAccountKey -ResourceGroupName $resourceGroup -Name $storageAccount

# Create an Azure Storage context using the first access key
$context = New-AzStorageContext -StorageAccountName $storageAccount -StorageAccountKey $key[0].value

# Create a file share named 'resource-templates' in your Azure Storage account
$fileShare = New-AzStorageShare -Name 'resource-templates' -Context $context

# Add the storageTemplate.json file to the new file share
Set-AzStorageFileContent -ShareName $fileShare.Name -Context $context -Source $storageTemplate

PowerShell runbook betiğini oluşturma

Azure Depolama dosyasını alan storageTemplate.json ve şablonu dağıtarak yeni bir Azure Depolama hesabı oluşturan bir PowerShell betiği oluşturun. adlı runbookScript.ps1 yerel bir dosya oluşturun ve aşağıdaki kodu yapıştırın:

param (
    [Parameter(Mandatory=$true)]
    [string]
    $resourceGroup,

    [Parameter(Mandatory=$true)]
    [string]
    $storageAccount,

    [Parameter(Mandatory=$true)]
    [string]
    $storageAccountKey,

    [Parameter(Mandatory=$true)]
    [string]
    $storageFileName,

    [Parameter(Mandatory=$true)]
    [string]
    $userAssignedManagedIdentity
)

# Ensures you do not inherit an AzContext in your runbook
Disable-AzContextAutosave -Scope Process

# Connect to Azure with user-assigned managed identity
$AzureContext = (Connect-AzAccount -Identity).context
$identity = Get-AzUserAssignedIdentity -ResourceGroupName $resourceGroup `
    -Name $userAssignedManagedIdentity `
    -DefaultProfile $AzureContext
$AzureContext = (Connect-AzAccount -Identity -AccountId $identity.ClientId).context

# set and store context
$AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription `
    -DefaultProfile $AzureContext

#Set the parameter values for the Resource Manager template
$Parameters = @{
    "storageAccountType"="Standard_LRS"
    }

# Create a new context
$Context = New-AzStorageContext -StorageAccountName $storageAccount -StorageAccountKey $storageAccountKey

Get-AzStorageFileContent `
    -ShareName 'resource-templates' `
    -Context $Context `
    -path 'storageTemplate.json' `
    -Destination 'C:\Temp' -Force

$TemplateFile = Join-Path -Path 'C:\Temp' -ChildPath $storageFileName

# Deploy the storage account
New-AzResourceGroupDeployment `
    -ResourceGroupName $resourceGroup `
    -TemplateFile $TemplateFile `
    -TemplateParameterObject $Parameters 

Runbook'u Azure Otomasyonu hesabınızda içeri aktarma ve yayımlama

Runbook'u Otomasyon hesabınıza aktarmak ve ardından runbook'u yayımlamak için PowerShell'i kullanın. Azure portalında runbook'ları içeri aktarma ve yayımlama hakkında bilgi için bkz. Azure Otomasyonu'de runbook'ları yönetme.

Otomasyon hesabınıza PowerShell runbook'u olarak aktarmak runbookScript.ps1 için aşağıdaki PowerShell komutlarını çalıştırın:

$importParams = @{
    Path = $runbookScript
    ResourceGroupName = $resourceGroup
    AutomationAccountName = $automationAccount
    Type = "PowerShell"
}
Import-AzAutomationRunbook @importParams

# Publish the runbook
$publishParams = @{
    ResourceGroupName = $resourceGroup
    AutomationAccountName = $automationAccount
    Name = "runbookScript"
}
Publish-AzAutomationRunbook @publishParams

Runbook’u başlatma

Şimdi Start-AzAutomationRunbook cmdlet'ini çağırarak runbook'u başlatıyoruz. Azure portalında runbook başlatma hakkında bilgi için bkz. Azure Otomasyonu'da runbook başlatma.

PowerShell konsolunda aşağıdaki komutları çalıştırın:

# Set up the parameters for the runbook
$runbookParams = @{
    resourceGroup = $resourceGroup
    storageAccount = $storageAccount
    storageAccountKey = $key[0].Value # We got this key earlier
    storageFileName = "storageTemplate.json"
    userAssignedManagedIdentity = $userAssignedManagedIdentity
}

# Set up parameters for the Start-AzAutomationRunbook cmdlet
$startParams = @{
    resourceGroup = $resourceGroup
    AutomationAccountName = $automationAccount
    Name = "runbookScript"
    Parameters = $runbookParams
}

# Start the runbook
$job = Start-AzAutomationRunbook @startParams

Runbook çalıştırıldıktan sonra, iş nesnesinin $job.Statusözellik değerini alarak durumunu de kontrol edebilirsiniz.

Runbook Resource Manager şablonunu alır ve yeni bir Azure Depolama hesabı dağıtmak için bu şablonu kullanır. Aşağıdaki komutu çalıştırarak yeni depolama hesabının oluşturulduğunu görebilirsiniz:

Get-AzStorageAccount

Sonraki adımlar