在 Azure 自动化 PowerShell Runbook 中部署 Azure 资源管理器模板Deploy an Azure Resource Manager template in an Azure Automation PowerShell runbook

可以编写一个 Azure 自动化 PowerShell Runbook,用于通过 Azure 资源管理模板部署 Azure 资源。You can write an Azure Automation PowerShell runbook that deploys an Azure resource by using an Azure Resource Management template.

这样,便可以将 Azure 资源的部署自动化。By doing this, you can automate deployment of Azure resources. 可以在一个安全的中心位置(例如 Azure 存储)维护资源管理器模板。You can maintain your Resource Manager templates in a central, secure location such as Azure Storage.

本文创建一个 PowerShell Runbook,该 Runbook 使用 Azure 存储中存储的资源管理器模板部署新的 Azure 存储帐户。In this article, we create a PowerShell runbook that uses a Resource Manager template stored in Azure Storage to deploy a new Azure Storage account.

先决条件Prerequisites

若要完成本教程,需要拥有以下项目:To complete this tutorial, you need the following items:

创建 Resource Manager 模板Create the Resource Manager template

在本示例中,我们使用用于部署新 Azure 存储帐户的资源管理器模板。For this example, we use a Resource Manager template that deploys a new Azure Storage account.

在文本编辑器中复制以下文本:In a text editor, copy the following text:

{
  "$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",
        "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')]"
      }
  }
}

将该文件在本地另存为 TemplateTest.json 。Save the file locally as TemplateTest.json.

在 Azure 存储中保存资源管理器模板Save the Resource Manager template in Azure Storage

现在,我们使用 PowerShell 创建 Azure 存储文件共享并上传 TemplateTest.json 文件。Now we use PowerShell to create an Azure Storage file share and upload the TemplateTest.json file. 有关如何在 Azure 门户中创建文件共享和上传文件的说明,请参阅在 Windows 上开始使用 Azure 文件存储For instructions on how to create a file share and upload a file in the Azure portal, see Get started with Azure File storage on Windows.

在本地计算机上启动 PowerShell,运行以下命令创建文件共享并将资源管理器模板上传到该文件共享。Launch PowerShell on your local machine, and run the following commands to create a file share and upload the Resource Manager template to that file share.

# Log into Azure
Connect-AzureRmAccount -Environment "AzureChinaCloud"

# Get the access key for your storage account
$key = Get-AzureRmStorageAccountKey -ResourceGroupName 'MyAzureAccount' -Name 'MyStorageAccount'

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

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

# Add the TemplateTest.json file to the new file share
# "TemplatePath" is the path where you saved the TemplateTest.json file
$templateFile = 'C:\TemplatePath'
Set-AzureStorageFileContent -ShareName $fileShare.Name -Context $context -Source $templateFile

创建 PowerShell Runbook 脚本Create the PowerShell runbook script

现在,我们创建一个 PowerShell 脚本,用于从 Azure 存储获取 TemplateTest.json 文件,并部署该模板以创建新的 Azure 存储帐户。Now we create a PowerShell script that gets the TemplateTest.json file from Azure Storage and deploys the template to create a new Azure Storage account.

在文本编辑器中粘贴以下文本:In a text editor, paste the following text:

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

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

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

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

# Authenticate to Azure if running from Azure Automation
$ServicePrincipalConnection = Get-AutomationConnection -Name "AzureRunAsConnection"
Login-AzureRmAccount `
    -ServicePrincipal `
    -TenantId $ServicePrincipalConnection.TenantId `
    -ApplicationId $ServicePrincipalConnection.ApplicationId `
    -CertificateThumbprint $ServicePrincipalConnection.CertificateThumbprint -EnvironmentName "AzureChinaCloud" | Write-Verbose

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

# Create a new context
$Context = New-AzureStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $StorageAccountKey

Get-AzureStorageFileContent -ShareName 'resource-templates' -Context $Context -path 'TemplateTest.json' -Destination 'C:\Temp'

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

# Deploy the storage account
New-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroupName -TemplateFile $TemplateFile -TemplateParameterObject $Parameters 

将该文件在本地另存为 DeployTemplate.ps1 。Save the file locally as DeployTemplate.ps1.

在 Azure 自动化帐户中导入并发布 RunbookImport and publish the runbook into your Azure Automation account

现在,我们使用 PowerShell 将 Runbook 导入 Azure 自动化帐户,并发布该 Runbook。Now we use PowerShell to import the runbook into your Azure Automation account, and then publish the runbook. 有关如何在 Azure 门户中导入和发布 Runbook 的信息,请参阅在 Azure 自动化中管理 RunbookFor information about how to import and publish a runbook in the Azure portal, see Manage runbooks in Azure Automation.

若要将 DeployTemplate.ps1 作为 PowerShell runbook 导入自动化帐户,请运行以下 PowerShell 命令:To import DeployTemplate.ps1 into your Automation account as a PowerShell runbook, run the following PowerShell commands:

# MyPath is the path where you saved DeployTemplate.ps1
# MyResourceGroup is the name of the Azure ResourceGroup that contains your Azure Automation account
# MyAutomationAccount is the name of your Automation account
$importParams = @{
    Path = 'C:\MyPath\DeployTemplate.ps1'
    ResourceGroupName = 'MyResourceGroup'
    AutomationAccountName = 'MyAutomationAccount'
    Type = 'PowerShell'
}
Import-AzureRmAutomationRunbook @importParams

# Publish the runbook
$publishParams = @{
    ResourceGroupName = 'MyResourceGroup'
    AutomationAccountName = 'MyAutomationAccount'
    Name = 'DeployTemplate'
}
Publish-AzureRmAutomationRunbook @publishParams

启动 RunbookStart the runbook

现在,通过调用 Start-AzureRmAutomationRunbook cmdlet 来启动该 Runbook。Now we start the runbook by calling the Start-AzureRmAutomationRunbook cmdlet.

有关如何在 Azure 门户中启动 Runbook 的信息,请参阅在 Azure 自动化中启动 RunbookFor information about how to start a runbook in the Azure portal, see Starting a runbook in Azure Automation.

在 PowerShell 控制台中运行以下命令:Run the following commands in the PowerShell console:

# Set up the parameters for the runbook
$runbookParams = @{
    ResourceGroupName = 'MyResourceGroup'
    StorageAccountName = 'MyStorageAccount'
    StorageAccountKey = $key[0].Value # We got this key earlier
    StorageFileName = 'TemplateTest.json' 
}

# Set up parameters for the Start-AzureRmAutomationRunbook cmdlet
$startParams = @{
    ResourceGroupName = 'MyResourceGroup'
    AutomationAccountName = 'MyAutomationAccount'
    Name = 'DeployTemplate'
    Parameters = $runbookParams
}

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

Runbook 将会运行。可以运行 $job.Status 检查其状态。The runbook runs, and you can check its status by running $job.Status.

Runbook 会获取资源管理器模板,并使用它来部署新的 Azure 存储帐户。The runbook gets the Resource Manager template and uses it to deploy a new Azure Storage account. 运行以下命令后,可以看到已创建新的存储帐户:You can see that the new storage account was created by running the following command:

Get-AzureRmStorageAccount

摘要Summary

就这么简单!That's it! 现在,可通过资源管理器模板使用 Azure 自动化和 Azure 存储来部署所有 Azure 资源。Now you can use Azure Automation and Azure Storage with Resource Manager templates to deploy all your Azure resources.

后续步骤Next steps