【问题标题】:Variable tags Azure ARM JSON based基于 Azure ARM JSON 的变量标签
【发布时间】:2018-11-30 14:12:58
【问题描述】:

我们正在使用以下模板通过 ARM 模板部署多个资源组:

"parameters": {
    "ResourceGroups": {
          "type": "array",
          "defaultValue": [
            "RG1",
            "RG2",
            "RG3"
          ]
        }
    "resources": [
          {
            "type": "Microsoft.Resources/resourceGroups",
            "apiVersion": "2018-05-01",
            "location": "[parameters('rgLocation')]",
            "name": "[parameters('ResourceGroups')[copyIndex()])]",
            "copy": {
              "name": "resourcegroupcopy",
              "count": "[length(parameters('ResourceGroups'))]",
              "mode": "serial"
            },
"properties": {},
        "tags": {}

我们还希望在这些资源组上编写 Azure 标记脚本。然而问题是,并非我们创建的所有资源组都需要相同的标签。它们因资源组而异。

例如:RG1需要Tag1,RG2需要Tag2等

如何将其放入我的脚本中?

谁能指出我正确的方向?

谢谢!

【问题讨论】:

  • 这就是变量的用途。

标签: json azure azure-resource-manager arm-template


【解决方案1】:

答案是:这取决于您的确切要求,但通常有两种方法:if() 函数、对象映射。其中任何一个都可以与 union() 函数结合使用。为您需要的每个标签创建一个变量:

"tag1": {
    "something": "bla-bla"
},
"tag2": {
    "somethingElse": "bla-bla-bla"
}

那么,你可以在资源代码中做这样的事情:

"tags": "[if(condition(something goes here, depending on your needs), variable('tag1'), variables('tag2'))]"

你可以有更多的 if 语句在另一个中组合,你也可以使用 union() 函数来合并标签(虽然,不实用)。联合(变量('tag1'),变量('tag2'))。

另一种(按比例更易于管理的方式)是使用映射器来“计算”标签属性。您希望 rg1 上的 tag1、rg2 上的 tag2、rg3 上的 tag3。简而言之,会发生什么:您正在检索一个变量,该变量的名称等于属性的值,而该属性的值又等于对象的名称。令人困惑?这是一个例子。创建一个新变量:

"mapper": {
    "rg1": "tag1",
    "rg2": "tag2",
    "rg3": "tag3",
}

然后,在您的资源中,您可以这样做:

"tags": "[variables(variables('mapper')[variables(parameters('ResourceGroups')[copyIndex()]))])]"
          ^         ^                  ^          ^ name of the property would be RG1\RG2\RG3 depending on where you are in the loop. this would return value of the property, so tag1 or tag2 or tag3
          ^         ^                  ^ access properties of the object you get from the previous function (variables('mapper'))
          ^         ^ get variable called 'mapper'. you will get an object
          ^ get variable value called tag1 or tag2 or tag3

【讨论】:

  • 太棒了,非常感谢!还有两个问题。如果所有资源组都需要相同的标签,但值不同怎么办?是否有某种最佳实践?如果是映射器,如果 rg1 同时需要 tag1 和 tag2 怎么办?
  • 好吧,您必须从某个地方提取值。由于 arm 模板并没有真正提供像集中存储这样的东西,您需要在运行模板并将值作为参数传递之前这样做,或者您需要实现一些创建 arm 模板策略;)
猜你喜欢
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-13
  • 2019-06-11
  • 1970-01-01
  • 2018-10-22
相关资源
最近更新 更多