Как я могу передать полностью квалифицированный идентификатор ресурса Azure как необработанный JSON, используя условную логику? - PullRequest
0 голосов
/ 27 июня 2019

Я пытаюсь условно передать полный идентификатор ресурса групп безопасности сети и таблиц маршрутизации в подсети внутри виртуальной сети.В настоящее время они развернуты с использованием итерации свойства arm на виртуальном сетевом ресурсе.

Я следовал этой статье, чтобы добраться до этой точки.https://github.com/MicrosoftDocs/azure-docs/issues/29115

Я успешно могу присоединить таблицы маршрутизации и nsgs к подсетям на основе заполненных значений свойств.Однако я не могу создать полный идентификатор ресурса, используя переменные и параметры для условного развертывания объектов.

Я пытался использовать функции Azure ARM, такие как subscription () и resource ().Однако всякий раз, когда я объединяю свою строку FQDN с помощью этих функций, я получаю сообщение об ошибке в JSON.Согласно статье выше, поддержка MSFT заявляет, что это должно быть передано через полностью квалифицированную, и я не смог придумать способ сделать это и преобразовать его с помощью функции json ().Я протестировал передачу через короткое имя идентификатора ресурса, и ARM API также сообщает, что мне нужно передать это как полностью определенное имя

Я действительно не хочу, чтобы они были жестко запрограммированы в верхней части моего шаблона, так как яне знаю, что такое идентификатор ресурса, пока эти объекты не будут созданы.Плюс это, очевидно, также плохая практика, побеждающая цель многоразового использования шаблона.

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "location": {
      "type": "string",
      "allowedValues": ["australiaeast", "australiasoutheast"],
      "defaultValue": "australiasoutheast",
      "metadata": {
        "description": "Deployment location"
      }
    },
    "routeTables": {
      "type": "array",
      "defaultValue": [
        "TrustedSubnets",
        "UntrustedSubnets"
      ],
      "metadata": {
        "description": "Array of interconnect route table names, (e.g. GatewaySubnet / Internal / Onprem)"
      }
    },
    "subnets": {
      "type": "array",
      "defaultValue": [
        {
          "Name": "Management",
          "Address": "10.118.124.0/24",
          "Nsg": "/sub/1234/resourceGroups/azresgroup/providers/Microsoft.Network/networkSecurityGroups/ManagementSn-ase-nsg",
          "routeTable": "/sub/1234/resourceGroups/azresgroup/providers/Microsoft.Network/routeTables/TrustedSubnets-ase-rt"
        },
        {
          "Name": "Trusted",
          "Address": "10.118.125.0/24",
          "Nsg": "/sub/1234/resourceGroups/azresgroup/providers/Microsoft.Network/networkSecurityGroups/TrustedSn-ase-nsg",
          "routeTable": "/sub/1234/resourceGroups/azresgroup/providers/Microsoft.Network/routeTables/TrustedSubnets-ase-rt"
        },
        {
          "Name": "Untrusted",
          "Address": "10.118.126.0/24",
          "Nsg": "/sub/1234/resourceGroups/azresgroup/providers/Microsoft.Network/networkSecurityGroups/UntrustedSn-ase-nsg",
          "routeTable": "/sub/1234/resourceGroups/azresgroup/providers/Microsoft.Network/routeTables/UntrustedSubnets-ase-rt"
        },
        {
          "Name": "GatewaySubnet",
          "Address": "10.118.127.0/24",
          "Nsg": "",
          "routeTable": ""
        }
      ],
      "metadata": {
        "description": "Subnet properties to be deployed per region. Each entry must contain a Name, Address, Nsg and routeTable key. Route tables and NSG's must be fully qualified"
      }
    },
    "vnetName": {
      "type": "string",
      "defaultValue": "hubvnet",
      "metadata": {
        "description": "Virtual network name"
      }
    },
    "vnetAddressPrefix": {
      "type": "string",
      "defaultValue": "10.118.124.0/22",
      "metadata": {
        "description": "Address prefix"
      }
    }
  },
  "variables": {
    "alertsDistributionList": "dl_azurevnetalerts@email.com.au",
    "HubNetAgResourceId": "[resourceId('microsoft.insights/actionGroups', concat(parameters('vnetName'), '-ag'))]",
    "vnetResourceId": "[resourceId('Microsoft.Network/virtualNetworks', concat(parameters('vnetName')))]"
  },
  "resources": [
    {
      "type": "Microsoft.Network/networkSecurityGroups",
      "apiVersion": "2019-04-01",
      "name": "[if(contains(parameters('location'), 'australiasoutheast'), concat(parameters('subnets')[copyIndex()].Name, 'Sn', '-ase-nsg'), concat(parameters('subnets')[copyIndex()].Name, 'Sn', '-ae-nsg'))]",
      "location": "[parameters('location')]",
      "copy": {
        "name": "NsgCopy",
        "count": 3,
        "mode": "Serial",
        "batchSize": 1
      },
      "properties": {
        "securityRules": []
      },
      "dependsOn": []
    },
    {
      "apiVersion": "2019-04-01",
      "name": "[if(contains(parameters('location'), 'australiasoutheast'), concat(parameters('routeTables')[copyIndex()], '-ase-rt'), concat(parameters('routeTables')[copyIndex()], '-ae-rt'))]",
      "type": "Microsoft.Network/routeTables",
      "location": "[resourceGroup().location]",
      "copy": {
        "name": "RtCopy",
        "count": "[length(parameters('routeTables'))]"
      },
      "properties": {
        "routes": [],
        "disableBgpRoutePropagation": true
      }
    },
    {
      "type": "Microsoft.Network/virtualNetworks",
      "name": "[parameters('vnetName')]",
      "apiVersion": "2019-04-01",
      "location": "[resourceGroup().location]",
      "properties": {
        "addressSpace": {
          "addressPrefixes": [
            "[parameters('vnetAddressPrefix')]"
          ]
        },
        "dhcpOptions": {
          "dnsServers": []
        },
        "virtualNetworkPeerings": [],
        "copy": [{
          "name": "subnets",
          "count": "[length(parameters('subnets'))]",
          "input": {
            "name": "[parameters('subnets')[copyIndex('subnets')].Name]",
            "properties": {
              "addressPrefix": "[parameters('subnets')[copyIndex('subnets')].Address]",
              "networkSecurityGroup": "[if(not(empty(parameters('subnets')[copyIndex('subnets')].Nsg)), json(concat('{\"id\": \"', parameters('subnets')[copyIndex('subnets')].Nsg, '\"}')), json('null'))]",
              "routeTable": "[if(not(empty(parameters('subnets')[copyIndex('subnets')].routeTable)), json(concat('{\"id\": \"', parameters('subnets')[copyIndex('subnets')].routeTable, '\"}')), json('null'))]" 
            }
          }
        }]
      },
      "dependsOn": [
        "NsgCopy",
        "RtCopy"
      ]
    }
  ]
}

Я бы хотел избежать жесткого кодирования идентификаторов ресурсов в свойствах моего параметра, где я объявляю массив подсетей.Я хотел бы, чтобы они генерировались с использованием интеллектуальной логики, а затем конвертировались и передавались в виде необработанного json в цикле подсети внизу

Я скрыл свой идентификатор Id в верхней части шаблона.Пожалуйста, замените ваши значения, если вы хотите проверить мой шаблон

Любая помощь с благодарностью.:)

Ответы [ 2 ]

0 голосов
/ 27 июня 2019

Спасибо за вашу помощь @ 4c74356b41 Ваше предложение было в большинстве случаев там. Мне просто нужно было немного развить логику, которая дала мне решение, которое я искал.Я отправил с рабочим решением ниже:)

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "location": {
      "type": "string",
      "allowedValues": ["australiaeast", "australiasoutheast"],
      "defaultValue": "australiasoutheast",
      "metadata": {
        "description": "Deployment location"
      }
    },
    "routeTables": {
      "type": "array",
      "defaultValue": [
        "TrustedSubnets",
        "UntrustedSubnets"
      ],
      "metadata": {
        "description": "Array of interconnect route table names, (legal values are -  TrustedSubnets or UntrustedSubnets )"
      }
    },
    "subnets": {
      "type": "array",
      "defaultValue": [
        {
          "Name": "Management",
          "Address": "192.168.1.0/24",
          "Nsg": "Yes",
          "routeTable": "TrustedSubnets"
        },
        {
          "Name": "Trusted",
          "Address": "192.168.2.0/24",
          "Nsg": "Yes",
          "routeTable": "TrustedSubnets"
        },
        {
          "Name": "Untrusted",
          "Address": "192.168.3.0/24",
          "Nsg": "Yes",
          "routeTable": "UntrustedSubnets"
        },
        {
          "Name": "GatewaySubnet",
          "Address": "192.168.4.0/24",
          "Nsg": "",
          "routeTable": ""
        }
      ],
      "metadata": {
        "description": "Subnet properties to be deployed per region. Each entry must contain a Name, Address, Nsg and routeTable key. Route tables and NSG's must be fully qualified"
      }
    },
    "vnetName": {
      "type": "string",
      "defaultValue": "hubvnet",
      "metadata": {
        "description": "Virtual network name"
      }
    },
    "vnetAddressPrefix": {
      "type": "string",
      "defaultValue": "192.168.1.0/22",
      "metadata": {
        "description": "Address prefix"
      }
    }
  },
  "variables": {
    "alertsDistributionList": "dl_azurevnetalerts@email.com.au",
    "HubNetAgResourceId": "[resourceId('microsoft.insights/actionGroups', concat(parameters('vnetName'), '-ag'))]",
    "vnetResourceId": "[resourceId('Microsoft.Network/virtualNetworks', concat(parameters('vnetName')))]",
    "copy": [
      {
          "name": "Nsgs",
          "count": "[length(parameters('subnets'))]",
          "input": {
              "id": "[if(contains(parameters('location'), 'australiasoutheast'), resourceId('Microsoft.Network/networkSecurityGroups', concat(parameters('subnets')[copyIndex('Nsgs')].Name, 'Sn', '-ase-nsg')), resourceId('Microsoft.Network/networkSecurityGroups', concat(parameters('subnets')[copyIndex('Nsgs')].Name, 'Sn', '-ae-nsg')))]"
          }
      },
      {
          "name": "routeTables",
          "count": "[length(parameters('subnets'))]",
          "input": {
              "id": "[if(contains(parameters('location'), 'australiasoutheast'), resourceId('Microsoft.Network/routeTables', concat(parameters('subnets')[copyIndex('routeTables')].routeTable, '-ase-rt')), resourceId('Microsoft.Network/routeTables', concat(parameters('subnets')[copyIndex('routeTables')].routeTable, '-ae-rt')))]"
          }
      }
  ]
},
  "resources": [
    {
      "type": "Microsoft.Network/networkSecurityGroups",
      "apiVersion": "2019-04-01",
      "name": "[if(contains(parameters('location'), 'australiasoutheast'), concat(parameters('subnets')[copyIndex()].Name, 'Sn', '-ase-nsg'), concat(parameters('subnets')[copyIndex()].Name, 'Sn', '-ae-nsg'))]",
      "location": "[parameters('location')]",
      "copy": {
        "name": "NsgCopy",
        "count": 3,
        "mode": "Serial",
        "batchSize": 1
      },
      "properties": {
        "securityRules": []
      },
      "dependsOn": []
    },
    {
      "apiVersion": "2019-04-01",
      "name": "[if(contains(parameters('location'), 'australiasoutheast'), concat(parameters('routeTables')[copyIndex()], '-ase-rt'), concat(parameters('routeTables')[copyIndex()], '-ae-rt'))]",
      "type": "Microsoft.Network/routeTables",
      "location": "[resourceGroup().location]",
      "copy": {
        "name": "RtCopy",
        "count": "[length(parameters('routeTables'))]"
      },
      "properties": {
        "routes": [],
        "disableBgpRoutePropagation": true
      }
    },
    {
      "type": "Microsoft.Network/virtualNetworks",
      "name": "[parameters('vnetName')]",
      "apiVersion": "2019-04-01",
      "location": "[resourceGroup().location]",
      "properties": {
        "addressSpace": {
          "addressPrefixes": [
            "[parameters('vnetAddressPrefix')]"
          ]
        },
        "dhcpOptions": {
          "dnsServers": []
        },
        "virtualNetworkPeerings": [],
        "copy": [{
          "name": "subnets",
          "count": "[length(parameters('subnets'))]",
          "input": {
            "name": "[parameters('subnets')[copyIndex('subnets')].Name]",
            "properties": {
              "addressPrefix": "[parameters('subnets')[copyIndex('subnets')].Address]",
              "networkSecurityGroup": "[if(not(empty(parameters('subnets')[copyIndex('subnets')].Nsg)), variables('Nsgs')[copyIndex('subnets')], json('null'))]",
              "routeTable": "[if(not(empty(parameters('subnets')[copyIndex('subnets')].routeTable)), variables('routeTables')[copyIndex('subnets')], json('null'))]" 
            }
          }
        }]
      },
      "dependsOn": [
        "NsgCopy",
        "RtCopy"
      ]
    }
  ]
}
0 голосов
/ 27 июня 2019

Я бы наверное сделал это:

"variables": {
    "copy": [
        {
            "name": "routeTables",
            "count": "[length(parameters('subnets'))]",
            "input": {
                "id": "[parameters('subnets')[copyIndex('routeTables')].routeTable]"
            }
        }
    ]
},

"properties": {
    ...
    "routeTable": "[if(not(empty(parameters('subnets')[copyIndex('subnets')].routeTable)), variables('routeTables')[copyIndex('subnets')], json('null'))]" 
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...