Я пытаюсь создать службу приложений для развертывания через конвейер CI/CD, однако я изо всех сил пытаюсь создать цикл For для строк подключения.
В моем файле параметров у меня есть следующее:
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
"contentVersion": "1.0.0.0",
"parameters": {
// Required Parameters
...
// Optional Parameters
"connectionStrings": [
{
"name": "Tracking",
"connectionString": "...",
"type": "SQLServer"
}
{
"name": "Logs",
"connectionString": "...",
"type": "SQLServer"
}
],
...
}
}
Я передаю это в файл main.bicep и файл модуля appService.bicep как param connectionStrings array.
В файле appService.bicep у меня есть следующий цикл for.
resource appServiceWeb 'Microsoft.Web/sites@2022-03-01' = {
name: nameWeb
location: location
tags: tags
kind: kind
identity: {
type: 'SystemAssigned'
}
properties: {
serverFarmId: appServicePlan_id
siteConfig: {
appSettings: [
...
]
connectionStrings: [for connectionString in connectionStrings: {
name: connectionString.name
connectionString: connectionString.connectionString
type: connectionString.type
}]
}
}
}
Я получаю следующую ошибку:
{
"code": "InvalidRequestContent",
"message": "The request content was invalid and could not be deserialized: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Azure.Deployments.Core.Definitions.DeploymentParameterDefinition' because the type requires a JSON object (e.g. {\"name\":\"value\"}) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON object (e.g. {\"name\":\"value\"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.\r\nPath 'properties.parameters.connectionStrings', line 1, position 280.'."
}
Мне удалось исправить мою проблему. Хотя моя структура Json была законной, она не подходила для файлов бицепсов.
Мне нужно было добавить часть value ниже:
"connectionStrings": {
"value": [
{
"name": "TrackingEntities",
"connectionString": "...",
"type": "SQLServer"
}
]
},
Вместо того, чтобы передавать connectionStrings в файл parameters.json, включите его с типом массива в файл main.bicep. Если вы передаете parameters.json, он ожидает тип объекта, и поэтому цикл for выдает ошибку десериализованного объекта.
Обычно, чтобы избежать этой ошибки, передайте цикл for как
[for (connectionStrings, i) in connectionStrings: {
connectionStrings : <ResourceName>.properties.connectionStrings[i]
}
В качестве альтернативы я бы посоветовал вам добавить файл main.bicep с ключевым словом param, как описано выше.
Обратившись к образцу шаблона бицепса, я внес несколько изменений в ваш код и смог успешно его развернуть.
Main.bicep:
param webAppName string = <AppNAme>
param sku string = '<SKU>'
param linuxFxVersion string = ''
param location string = resourceGroup().location
var appServicePlanName = <appServicePlanName>
var webSiteName = <webSiteName>
param connectionStrings array = [
{
name: 'Tracking'
connectionString: ''
type: 'SQLServer'
}
{
name: 'Logs'
connectionString: ''
type: 'SQLServer'
}
]
resource appServicePlan 'Microsoft.Web/serverfarms@2020-06-01' = {
name: appServicePlanName
location: location
properties: {
reserved: true
}
sku: {
name: sku
}
kind: 'linux'
}
resource appService 'Microsoft.Web/sites@2020-06-01' = {
name: webSiteName
location: location
properties: {
serverFarmId: appServicePlan.id
siteConfig: {
linuxFxVersion: linuxFxVersion
connectionStrings: [for connectionString in connectionStrings: {
name: connectionString.name
connectionString: connectionString.connectionString
}]
}
}
}
Сборка и развертывание прошли успешно:
Успешно развернуто веб-приложение:
Добавлены строки подключения в WebApp -> Configuration:
У меня есть альтернативный подход с ключевым словом param. Сообщество может помочь вам дать четкий ответ.