Azurerm 3.x版本:除count外如何按输入变量条件创建App Service
Azurerm v3下根据OS类型选择创建Web App的替代方案
除了使用count参数,你可以通过以下两种更灵活的方式实现根据var.kind选择创建azurerm_windows_web_app或azurerm_linux_web_app:
1. 使用for_each替代count
for_each通过集合元素控制资源创建,相比count的索引式控制,可读性和后续引用的直观性更强。
先定义本地映射明确OS与资源类型的对应关系,再在资源块中用for_each过滤:
locals { web_app_kind_map = { Windows = "windows" Linux = "linux" } } resource "azurerm_service_plan" "app_service_plan" { name = local.name location = var.location resource_group_name = var.resource_group_name tags = var.tags os_type = var.os_type } resource "azurerm_windows_web_app" "app_service" { # 仅当var.kind为Windows时创建该资源 for_each = var.kind == "Windows" ? toset([var.kind]) : toset([]) name = local.name location = var.location resource_group_name = var.resource_group_name service_plan_id = azurerm_service_plan.app_service_plan.id } resource "azurerm_linux_web_app" "app_service" { # 仅当var.kind为Linux时创建该资源 for_each = var.kind == "Linux" ? toset([var.kind]) : toset([]) name = local.name location = var.location resource_group_name = var.resource_group_name service_plan_id = azurerm_service_plan.app_service_plan.id }
后续引用资源时,可以直接通过azurerm_windows_web_app.app_service["Windows"]或azurerm_linux_web_app.app_service["Linux"]精准获取,避免了count索引可能带来的歧义。
2. 拆分为独立子模块
如果Windows和Linux Web App需要不同的配置逻辑(比如Linux的容器部署、Windows的.NET版本设置),可以将两种Web App分别封装成子模块,在主模块中根据var.kind选择调用:
步骤1:创建子模块
- 新建
modules/web-app-windows/main.tf,封装Windows Web App配置:
variable "name" {} variable "location" {} variable "resource_group_name" {} variable "service_plan_id" {} resource "azurerm_windows_web_app" "app_service" { name = var.name location = var.location resource_group_name = var.resource_group_name service_plan_id = var.service_plan_id # 可添加Windows专属配置,比如site_config等 }
- 新建
modules/web-app-linux/main.tf,封装Linux Web App配置:
variable "name" {} variable "location" {} variable "resource_group_name" {} variable "service_plan_id" {} resource "azurerm_linux_web_app" "app_service" { name = var.name location = var.location resource_group_name = var.resource_group_name service_plan_id = var.service_plan_id # 可添加Linux专属配置,比如docker_container_settings等 }
步骤2:主模块中调用子模块
resource "azurerm_service_plan" "app_service_plan" { name = local.name location = var.location resource_group_name = var.resource_group_name tags = var.tags os_type = var.os_type } module "web_app_windows" { source = "./modules/web-app-windows" count = var.kind == "Windows" ? 1 : 0 name = local.name location = var.location resource_group_name = var.resource_group_name service_plan_id = azurerm_service_plan.app_service_plan.id } module "web_app_linux" { source = "./modules/web-app-linux" count = var.kind == "Linux" ? 1 : 0 name = local.name location = var.location resource_group_name = var.resource_group_name service_plan_id = azurerm_service_plan.app_service_plan.id }
这种方式将不同OS的配置逻辑解耦,便于后续维护和扩展各自的专属参数,让主模块结构更简洁。
内容的提问来源于stack exchange,提问作者simmyk
相关产品推荐
相关产品推荐

