Terraform中azurerm_linux_function_app的可选IP限制配置问题
实现Azure Linux函数应用访问限制二选一配置
要实现子网ID和IP地址限制的二选一配置,你需要调整变量定义、添加参数验证逻辑,并动态生成对应的ip_restriction块,确保两种限制方式不会同时生效。
步骤1:调整变量定义
完善变量,明确两个限制参数的互斥关系,并添加默认值:
variable "function_app_name" { type = string description = "Name of the Linux Function App" } variable "resource_group_name" { type = string description = "Name of the resource group" } variable "storage_account_name" { type = string description = "Name of the storage account linked to the Function App" } variable "service_plan_id" { type = string description = "ID of the App Service Plan for the Function App" } variable "enable_restriction" { type = bool description = "Toggle to enable access restriction" default = false } variable "subnet_id" { type = string description = "VNET subnet ID for access restriction (mutually exclusive with ip_address)" default = "" } variable "ip_address" { type = string description = "IP/CIDR address for access restriction (mutually exclusive with subnet_id)" default = "" }
步骤2:添加参数验证与动态配置
在函数应用资源块中添加验证逻辑,并根据参数动态生成访问规则:
resource "azurerm_linux_function_app" "function_app" { name = var.function_app_name resource_group_name = var.resource_group_name location = "northeurope" storage_account_name = var.storage_account_name service_plan_id = var.service_plan_id identity { type = "SystemAssigned" } # 验证互斥参数,避免同时配置两种限制 validation { condition = var.enable_restriction ? (length(var.subnet_id) > 0) != (length(var.ip_address) > 0) : true error_message = "When enable_restriction is true, provide either subnet_id OR ip_address, not both." } site_config { dynamic "ip_restriction" { for_each = var.enable_restriction ? [1] : [] content { # 根据非空参数生成对应限制规则 virtual_network_subnet_id = length(var.subnet_id) > 0 ? var.subnet_id : null ip_address = length(var.ip_address) > 0 ? var.ip_address : null priority = 100 # 设置优先级避免规则冲突 action = "Allow" # 默认允许指定来源访问 } } application_stack { python_version = "3.8" } } }
配置说明
- 当
enable_restriction设为true时:- 仅提供
subnet_id:仅允许指定子网内的流量访问函数应用 - 仅提供
ip_address:仅允许指定IP/CIDR段的流量访问函数应用
- 仅提供
- 验证逻辑会阻止同时传入两个参数的情况,避免Azure配置冲突
priority字段用于区分多条限制规则的执行顺序,可根据实际需求调整
内容的提问来源于stack exchange,提问作者gjgjgjgj14
相关产品推荐
相关产品推荐

