在Azure资源管理器(ARM)模板中,循环引用是指两个或多个资源相互依赖,形成一个闭环,这会导致部署失败。在使用Web App和SQL数据库时,可能会遇到这种情况。以下是一些基础概念和相关解决方案:
问题:在ARM模板中定义Web App和SQL数据库时,可能会遇到循环引用的问题。 原因:
dependsOn
确保资源的依赖关系明确,使用dependsOn
属性来指定资源的创建顺序。
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"resources": [
{
"type": "Microsoft.Sql/servers/databases",
"apiVersion": "2020-08-01-preview",
"name": "myDatabase",
"location": "[resourceGroup().location]",
"properties": {
"collation": "SQL_Latin1_General_CP1_CI_AS",
"edition": "Basic",
"maxSizeBytes": 104857600,
"requestedServiceObjectiveName": "Basic"
},
"dependsOn": []
},
{
"type": "Microsoft.Web/sites",
"apiVersion": "2020-10-01",
"name": "myWebApp",
"location": "[resourceGroup().location]",
"properties": {
"serverFarmId": "[resourceId('Microsoft.Web/serverfarms', 'myAppServicePlan')]"
},
"dependsOn": [
"myDatabase"
]
}
]
}
outputs
和parameters
通过输出参数和输入参数来解耦资源之间的直接依赖。
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"databaseConnectionString": {
"type": "string"
}
},
"resources": [
{
"type": "Microsoft.Sql/servers/databases",
"apiVersion": "2020-08-01-preview",
"name": "myDatabase",
"location": "[resourceGroup().location]",
"properties": {
"collation": "SQL_Latin1_General_CP1_CI_AS",
"edition": "Basic",
"maxSizeBytes": 104857600,
"requestedServiceObjectiveName": "Basic"
}
},
{
"type": "Microsoft.Web/sites",
"apiVersion": "2020-10-01",
"name": "myWebApp",
"location": "[resourceGroup().location]",
"properties": {
"serverFarmId": "[resourceId('Microsoft.Web/serverfarms', 'myAppServicePlan')]",
"siteConfig": {
"appSettings": [
{
"name": "DB_CONNECTION_STRING",
"value": "[parameters('databaseConnectionString')]"
}
]
}
},
"dependsOn": [
"myDatabase"
]
}
],
"outputs": {
"databaseConnectionString": {
"type": "string",
"value": "[concat('Server=tcp:', reference('myDatabase').fullyQualifiedDomainName, ';Initial Catalog=myDatabase;User ID=myUsername@myServer;Password=myPassword;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;')]"
}
}
}
通过明确资源的依赖关系和使用输出参数,可以有效避免ARM模板中的循环引用问题。确保在部署过程中资源的创建顺序正确,并且通过参数化配置来解耦资源之间的直接依赖。
领取专属 10元无门槛券
手把手带您无忧上云