创建资源组并部署资源

时间:2019-02-21 23:18:51

标签: azure azure-resource-manager azure-deployment

根据Microsoft Documentation,现在可以创建资源组并将资源部署到新创建的资源组。不过,一开始我们有一个小问题-

  

订阅级部署在以下方面与资源组部署不同:

     

架构和命令

     

用于订阅级部署的架构和命令与资源组部署不同。

     

对于架构,请使用https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#

这引发了一个主要问题,因为 azuredeploy.json 不再被视为部署模板,因为它没有使用资源部署架构(https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#)。

因此,另一种选择是将资源组创建为 嵌套模板 ,并为将要使用的子资源放置 dependsOn 创建后,现在允许我部署/验证文件。但是,这具有新问题。即使DependsOn指示已创建资源组,它仍然无法识别该资源组并返回错误-无法找到资源组,因此无法部署资源。我尝试使用链接模板(我知道这没有任何区别,但仍然如此)

有人设法做到这一点吗?

  • 同时创建资源组和部署资源。
  • 克服了尝试使用DependsOn的障碍,而仍然没有获得正确的部署或验证?

添加我的代码。

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "location": {
      "type": "string",
      "defaultValue": "North Europe"
    },
    "FirstResourceGroupName": {
      "type": "string",
      "defaultValue": "myFirstRG"
    },
    "FirstBlobStorageName": {
      "type": "string",
      "defaultValue": "North Europe"
    }
  },
  "variables": {
  },
  "resources": [
    {
      "type": "Microsoft.Resources/deployments",
      "apiVersion": "2018-05-01",
      "name": "ResourceGroupDeployment",
      "properties": {
        "mode": "Incremental",
        "template": {
          "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
          "contentVersion": "1.0.0.1",
          "resources": [
            {
              "type": "Microsoft.Resources/resourceGroups",
              "apiVersion": "2018-05-01",
              "location": "[parameters('location')]",
              "name": "[parameters('FirstResourceGroupName')]",
              "properties": {}
            }
          ],
          "outputs" : {}
        }
      }
    },
    {
      //ResourceDeployment
      "type": "Microsoft.Resources/deployments",
      "name": "StorageDeployment",
      "apiVersion": "2017-05-10",
      "dependsOn": [
        "[concat('Microsoft.Resources/deployments/', 'ResourceGroupDeployment')]"
        //"ResourceGroupDeployment"
      ],
      "resourceGroup": "[parameters('FirstResourceGroupName')]",
      "properties": {
        "mode": "Incremental",
        "template": {
            "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
            "contentVersion": "1.0.0.0",
            "parameters": {},
            "variables": {},
            "resources": [
                {
                    "type": "Microsoft.Storage/storageAccounts",
                    "apiVersion": "2017-10-01",
                    "name": "[parameters('FirstBlobStorageName')]",
                    "location": "[parameters('location')]",
                    "kind": "StorageV2",
                    "sku": {
                        "name": "Standard_LRS"
                    }
                }
            ],
            "outputs": {}
        }
      }
    } 
  ],
  "outputs": {}
}

2 个答案:

答案 0 :(得分:1)

当您不使用Visual Studio或Portal进行部署时,MS提出的解决方案很好。我的主要问题是模板的验证,该模板再次不适用于订阅级别的部署,因为它使用的架构没有重新定义为ARM。

它可以通过其他任何方式(例如cli \ sdks \ rest api)按照@ 4c74356b41的建议工作, ,但我没有走这条路。

我的另一个解决方案是通过在Azure DevOps管道上添加一个步骤来运行Powershell脚本。我是最接近完成这项工作的人,但是再次进行验证以检查我的部署是否成功,仍在进行中。我不希望我的发布管道因模板无效而失败。

这是我收集的内容,验证失败(即使在部署RG并使用 dependsOn 时也失败)的原因是,在部署模板之前不会创建资源组。除非通过资源组不存在的验证,否则模板部署不会发生。因此,我们陷入了循环。这两个选项是在验证之前在门户网站上手动创建它们(这违背了自动化的观点),或者在验证它们之前使用了简单的powershell步骤。后者就是我所追求的。我知道这是非正统的,但是可以....并且还可以验证我的模板。

注意-解决方案与原始问题不同,因为我使用了多个资源组创建功能。根据MS文档,您最多可以通过这种方式部署5个RG。

首先,创建一个资源组文件,该文件将保存要创建的资源组。它将是一个简单的JSON文件,例如

{
  "rgNames": 
  {
    "rg1": { "rg": "resource-group-main" },
    "rg2": { "rg": "resource-group-backup" }
  }
}

使用与您添加到该文件中的值相同的值作为参数,以便您可以使用它们将资源部署到其中。

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
      "ResourceGroups": {
          "type": "object",
          //If you are changing this value !!!! Please make sure you are also updating the same in the ResourceGroups.ARM.json !!!!
          "allowedValues": [
            {
              "rgNames": 
              {
                "rg1": { "rg": "resource-group-main" },
                "rg2": { "rg": "resource-group-backup" }
              }
            }
          ]
        }
    } 

第二,更改PS脚本,使其包含将循环遍历需要部署的资源组列表的代码。

# Set '$RGTemplateFile' parameter to be the name of the file you added to your project 
$rgFile = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($PSScriptRoot, $RGTemplateFile))

$rgString = Get-Content -Raw -Path $rgFile | ConvertFrom-Json

# helper to turn PSCustomObject into a list of key/value pairs
function Get-ObjectMembers {
   [CmdletBinding()]
   Param(
       [Parameter(Mandatory=$True, ValueFromPipeline=$True)]
       [PSCustomObject]$obj
   )
   $obj | Get-Member -MemberType NoteProperty | ForEach-Object {
       $key = $_.Name
       [PSCustomObject]@{Key = $key; Value = $obj."$key"}
   }
}

$rgValues = $jsonParam | Get-ObjectMembers | foreach {
   $_.Value | Get-ObjectMembers | foreach {
       [PSCustomObject]@{
           RGName = $_.value.rgNames | select -First 1
       }
   }
}

foreach ($values in $rgValues)
{
   New-AzureRmResourceGroup -Name $values.RGName -Location $ResourceGroupLocation -Verbose -Force
}

在执行验证之前添加上述代码-

if ($ValidateOnly) {
    $ErrorMessages = Format-ValidationOutput (Test-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroupName `
                                                                                  -TemplateFile $TemplateFile `
                                                                                  -TemplateParameterFile $TemplateParametersFile `
                                                                                  @OptionalParameters)
:

最后,更改部署模板文件(azuredeploy.json),以执行嵌套模板部署或链接模板,以在您声明的RG上部署资源。看起来更整洁了

  "variables": {
    "rg1Name": "[parameters('ResourceGroups')['rgNames']['rg1'].rg]",
    "rg2Name": "[parameters('ResourceGroups')['rgNames']['rg2'].rg]",
    "blob1Name": "[parameters('blob1')]",
    "blob2Name": "[parameters('blob2')]",
    "arm1": "[concat(parameters('_artifactsLocation'), 'rg1/rg1.ARM.json', parameters('_artifactsLocationSasToken'))]",
    "arm2": "[concat(parameters('_artifactsLocation'), 'rg2/rg2.ARM.json', parameters('_artifactsLocationSasToken'))]"
  },
  "resources": [
    {
      //RG1 Resources Deployment
      "type": "Microsoft.Resources/deployments",
      "name": "RG1Resources",
      "apiVersion": "2017-05-10",
      "resourceGroup": "[variables('rg1Name')]",
      "properties": {
        "mode": "Incremental",
        "templateLink": {
          "uri": "[variables('arm1')]",
          "contentVersion": "1.0.0.0"
        },
        "parameters": {
          "blob1Name": {
            "value": "[variables('blob1Name')]"
          }
        }
      }
    },
    {
      //RG2 Resources Deployment
      "type": "Microsoft.Resources/deployments",
      "name": "RG2Resources",
      "apiVersion": "2017-05-10",
      "resourceGroup": "[variables('rg2Name')]",
      "properties": {
        "mode": "Incremental",
        "templateLink": {
          "uri": "[variables('arm2')]",
          "contentVersion": "1.0.0.0"
        },
        "parameters": {
          "blobName": {
            "value": "[variables('blob2Name')]"
          }
        }
      }
    }
  ],
  "outputs": {}
}

您的rg1.ARM.json和rg2.ARM.json文件看起来很明显,一个文件可能拥有多个资源。

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {    
    "blobName": {
      "type": "string"
    }
  },
  "variables": {
  },
  "resources": [
    {
      "type": "Microsoft.Storage/storageAccounts",
      "name": "[parameters('blobName')]",
      "kind": "StorageV2",
      "apiVersion": "2018-07-01",
      "location": "[resourceGroup().location]",
      "sku": {
        "name": "Standard_LRS"
      },
      "properties": {}
    }
  ],
  "outputs": {
  }
}

设置完成后,您将能够验证文件,因为PS脚本会在通过验证之前为您创建RG。

答案 1 :(得分:0)

摘自官方文档的示例:

{
    "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
    "contentVersion": "1.0.0.1",
    "parameters": {
        "rgName": {
            "type": "string"
        },
        "rgLocation": {
            "type": "string"
        },
        "storagePrefix": {
            "type": "string",
            "maxLength": 11
        }
    },
    "variables": {
        "storageName": "[concat(parameters('storagePrefix'), uniqueString(subscription().id, parameters('rgName')))]"
    },
    "resources": [
        {
            "type": "Microsoft.Resources/resourceGroups",
            "apiVersion": "2018-05-01",
            "location": "[parameters('rgLocation')]",
            "name": "[parameters('rgName')]",
            "properties": {}
        },
        {
            "type": "Microsoft.Resources/deployments",
            "apiVersion": "2018-05-01",
            "name": "storageDeployment",
            "resourceGroup": "[parameters('rgName')]",
            "dependsOn": [
                "[resourceId('Microsoft.Resources/resourceGroups/', parameters('rgName'))]"
            ],
            "properties": {
                "mode": "Incremental",
                "template": {
                    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
                    "contentVersion": "1.0.0.0",
                    "parameters": {},
                    "variables": {},
                    "resources": [
                        {
                            "type": "Microsoft.Storage/storageAccounts",
                            "apiVersion": "2017-10-01",
                            "name": "[variables('storageName')]",
                            "location": "[parameters('rgLocation')]",
                            "kind": "StorageV2",
                            "sku": {
                                "name": "Standard_LRS"
                            }
                        }
                    ]
                }
            }
        }
    ]
}

完全满足您的需求。

https://docs.microsoft.com/en-us/azure/azure-resource-manager/deploy-to-subscription#create-resource-group-and-deploy-resources