首页 > 解决方案 > 使用嵌套的“reference()”调用时出现 InvalidTemplate 错误

问题描述

我试图在 ARM 模板中获取私有链接的私有 IP 地址,作为部署私有链接端点的一部分,它是相应的私有 DNS 条目。我能够为与专用端点关联的 NIC 找到正确的资源 id,但是当我尝试将该 id 直接传递到对其的调用中时reference()会失败并出现InvalidTemplate错误。

这是一个演示该问题的模板:

{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "privateEndpointName": {
            "type": "string"
        }
    },
    "variables": {
    },
    "resources": [
    ],
    "outputs": {
        "nic": {
            "type": "object",
            "value": "[reference(reference(resourceId('Microsoft.Network/privateEndpoints',parameters('privateEndpointName')), '2019-09-01').networkInterfaces[0].id, '2019-07-01')]"
        }
    },
    "functions": []
}

这失败了:

The template output 'nic' at line '14' and column '16' is not valid: The template function 'reference' is not expected at this location. Please see https://aka.ms/arm-template-expressions for usage details...

标签: azureazure-resource-manager

解决方案


您可以通过在收集器模式中使用嵌套模板来实现这一点。

https://docs.microsoft.com/en-us/azure/architecture/building-blocks/extending-templates/collector

在此模型中,您可能需要两个嵌套模板部署:

  1. 第一个模板将在私有端点上执行引用并将其设置为输出。
  2. 第二个模板将为私有端点获取一个参数,然后执行第二个引用并将其设置为输出。
  3. 在父模板中,您可以访问第二个嵌套模板的输出。

你可以用一个来实现它,但是模板变得有点难以阅读。这是有关如何执行此操作的粗略示例。您可能需要修复一些位,但总体思路应该保持不变。(“[[”告诉模板在第二个(嵌套)模板的上下文中解析模板函数,所有“[”都将在第一个模板的上下文中解析)。

{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    “参数”: {
        “私人端点名称”:{
            “类型”:“字符串”
        }
    },
    “变量”:{},
    “资源”: [
        {
            "type": "Microsoft.Resources/deployments",
            "apiVersion": "2015-01-01",
            "name": "privateEndpointDeployment",
            “特性”: {
                “模式”:“增量”,
                “参数”: {
                    "nicId": { "value": "[reference(resourceId('Microsoft.Network/privateEndpoints',parameters('privateEndpointName')), '2019-09-01').networkInterfaces[0].id]" }
                },
                “模板”: {
                    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
                    "contentVersion": "1.0.0.0",
                    “参数”: {
                        “nicId”:{
                            “类型”:“字符串”
                        }
                    },
                    “变量”:{},
                    “资源”: [],
                    “输出”:{
                        “尼克”:{
                            “类型”:“对象”,
                            “值”:“[[参考(参数('nicId'),'2019-07-01')]”
                        }
                    }
                }
            }
        }
    ],
    “输出”:{
        “尼克”:{
            “类型”:“对象”,
            “价值”:“[参考('privateEndpointDeployment','2015-01-01').outputs.nic.value]”
        }
    }
}

推荐阅读