Используйте ARM для создания подписки на сетку событий, чтобы собирать события для подписки. - PullRequest
0 голосов
/ 30 марта 2020

Обычно я пытаюсь использовать ARM для развертывания подписки на сетку событий для сбора определенных c событий внутри подписки (Topi c Types = Azure Подписки). У меня уже есть приложение-функция с созданной функцией триггера сетки событий, просто нужно t ie функция с подпиской сетки событий в качестве веб-крюка.

Я использую конвейер выпуска в Azure DevOps для автоматизировать весь этот рабочий процесс.

Вот один из примеров, который я использовал:

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "egstopic": {
      "type": "string",
      "defaultValue": "egstopic1",
      "metadata": {
        "description": "Event grid system topic"
      }
    },
    "eventSubName": {
      "type": "string",
      "defaultValue": "esub1",
      "metadata": {
        "description": "Event grid system topic"
      }
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]",
      "metadata": {
        "description": "Location for all resources."
      }
    },
    "eventGridFunc":{
        "type": "string",
        "defaultValue": "VmAddedListener",
        "metadata": {
            "description" : "Function Name"
        }
      }
    },
  "variables": {
    "functionUrl" : "[concat('https://', variables('FunctionAppName'),'.azurewebsites.net/runtime/webhooks/eventgrid?functionName=', parameters('eventGridFunc'),'&code=')]",
    "functionAppName": "event-driven-func2"
  },
  "resources": [
    {
        "type": "Microsoft.EventGrid/Topics",
        "apiVersion": "2018-01-01",
        "name": "[parameters('egstopic')]",
        "location": "[parameters('location')]",
        "properties":{}
    },
    {
    "type": "Microsoft.EventGrid/Topics/providers/eventSubscriptions",
    "name": "[concat(parameters('egstopic'), '/Microsoft.EventGrid/', parameters('eventSubName'))]",
    "location": "[parameters('location')]",
    "apiVersion": "2018-01-01",
    "dependsOn": [
                "[parameters('egstopic')]"
            ],
    "properties": {
        "destination": {
            "endpointType": "WebHook",
            "properties": {
                "endpointUrl": "[concat(variables('functionUrl'), listKeys(resourceId('Microsoft.Web/sites/host/', variables('functionAppName'), 'default'),'2016-08-01').masterKey)]"
            }
        },
        "filter": {
            "includedEventTypes": [
                "Microsoft.Resources.ResourceWriteSuccess"
            ],
            "advancedFilters": [
                {
                "key": "data.operationName",
                "operatorType": "StringContains",
                "values": [
                    "Microsoft.Compute/virtualMachines/write"
                ]
                }
            ] 
        }           
        }
    }
  ]
}

Это закончилось развертыванием сетки событий topi c вместо подписки на сетку событий.

Тогда мне предложили попробовать следующее:

{
  "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#",
  "contentVersion": "1.0.0.1",
  "parameters": {
    "egstopic": {
      "type": "string",
      "defaultValue": "egstopic1",
      "metadata": {
        "description": "Event grid system topic"
      }
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]",
      "metadata": {
        "description": "Location for all resources."
      }
    },
    "eventGridFunc":{
        "type": "string",
        "defaultValue": "VmAddedListener",
        "metadata": {
            "description" : "Function Name"
        }
      }
    },
  "variables": {
    "functionUrl" : "[concat('https://', variables('FunctionAppName'),'.azurewebsites.net/runtime/webhooks/eventgrid?functionName=', parameters('eventGridFunc'),'&code=')]",
    "functionAppName": "event-driven-func2",
    "eventSubName": "[concat('esub',uniquestring(resourceGroup().id))]",
    "eventSubTopic": "[concat('/subscriptions/',subscription().subscriptionid)]"

  },
  "resources": [
      {
        "type": "Microsoft.EventGrid/systemTopics/eventSubscriptions",
        "name": "eventSubEG1",
        "location": "[parameters('location')]",
        "apiVersion": "2020-04-01-preview",
        "properties": {
            "destination": {
                "endpointType": "WebHook",
                "properties": {
                    "endpointUrl": "[concat(variables('functionUrl'), listKeys(resourceId('Microsoft.Web/sites/host/', variables('functionAppName'), 'default'),'2016-08-01').masterKey)]"
                }
            },
            "filter": {
                "includedEventTypes": [
                    "Microsoft.Resources.ResourceWriteSuccess"
                ],
                "advancedFilters": [
                    {
                    "key": "data.operationName",
                    "operatorType": "StringContains",
                    "values": [
                        "Microsoft.Compute/virtualMachines/write"
                    ]
                    }
                ] 
            }           
          }
      }
    ]
}

Но это закончилось неудачей с этой ошибкой: A nested resource type must have identical number of segments as its resource name. A root resource type must have segment length one greater than its resource name

Просто нужно найти способ использовать ARM или Azure DevOps для автоматизации этого процесса.

1 Ответ

0 голосов
/ 01 апреля 2020

У меня есть обновленный шаблон на основе ваших шаблонов, я проверил этот шаблон, и он работает нормально. Он создает таблицу событий Topi c и подписку и связывает с ней функцию триггера событий.

{
    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "eventGridTopicName": {
            "type": "String",
            "metadata": {
                "description": "The name of the Event Grid custom topic."
            }
        },
        "eventGridSubscriptionName": {
            "type": "String",
            "metadata": {
                "description": "The name of the Event Grid custom topic's subscription."
            }
        },
        "eventGridSubscriptionURL": {
            "type": "String",
            "metadata": {
                "description": "Event grid subscription URL."
            }
        },
        "location": {
            "defaultValue": "[resourceGroup().location]",
            "type": "String",
            "metadata": {
                "description": "The location in which the Event Grid resources should be deployed."
            }
        }
    },
    "resources": [
        {
            "type": "Microsoft.EventGrid/topics",
            "apiVersion": "2018-01-01",
            "name": "[parameters('eventGridTopicName')]",
            "location": "[parameters('location')]"
        },
        {
            "type": "Microsoft.EventGrid/topics/providers/eventSubscriptions",
            "apiVersion": "2018-01-01",
            "name": "[concat(parameters('eventGridTopicName'), '/Microsoft.EventGrid/', parameters('eventGridSubscriptionName'))]",
            "location": "[parameters('location')]",
            "dependsOn": [
                "[parameters('eventGridTopicName')]"
            ],
            "properties": {
                "destination": {
                    "endpointType": "WebHook",
                    "properties": {
                        "endpointUrl": "[parameters('eventGridSubscriptionURL')]"
                    }
                },
                "filter": {
                    "includedEventTypes": [
                        "All"
                    ]
                }
            }
        }
    ]
}

Вы можете скопировать URL-адрес подписки сетки событий, перейдя в меню «Приложение» - «Функции» -> «Триггер сетки событий». Функция -> вкладка Интеграция. На этой вкладке вы найдете копию URL подписки на сетку событий, которая будет предоставлена ​​в качестве входных данных для шаблона.

enter image description here

Надеюсь, это поможет!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...