😀

Terraform で Web Apps の送信 IP アドレスを別の Web Apps のアクセス制限に入れてみた

に公開

Web Apps や Functions など Azure App Service を基盤としたアプリで送信元の IP アドレスを制限したい場合があります。Azure ポータルからアプリのネットワーク設定にアクセス制限を登録すれば良いのですが、送信元が Web Apps の場合 IP アドレスが 27 もあったりして手作業ではとても辛くなります。そこで、せっかく Terraform を使っているのだから動的に取得した Web Apps の送信 IP アドレスを、別の Web Apps のアクセス制限に入れてみる検証をしてみました。

検証用の main.tf を作成

リソースグループと App Service Plan を作り、Web Apps を 2 つ用意します。

main.tf
provider "azurerm" {
  features {}
}

variable "prefix" {
  type    = string
  default = "mnrwebfn"
}

resource "azurerm_resource_group" "rg" {
  name     = "${var.prefix}-rg"
  location = "japaneast"
}

resource "azurerm_service_plan" "plan" {
  name                = "${var.prefix}-plan"
  resource_group_name = azurerm_resource_group.rg.name
  location            = azurerm_resource_group.rg.location
  os_type             = "Linux"
  sku_name            = "B1"
}

resource "azurerm_linux_web_app" "web" {
  name                = "${var.prefix}-web"
  resource_group_name = azurerm_resource_group.rg.name
  location            = azurerm_resource_group.rg.location
  service_plan_id     = azurerm_service_plan.plan.id

  site_config {}
}

resource "azurerm_linux_web_app" "fun" {
  name                = "${var.prefix}-fun"
  resource_group_name = azurerm_resource_group.rg.name
  location            = azurerm_resource_group.rg.location
  service_plan_id     = azurerm_service_plan.plan.id

  site_config {
    dynamic "ip_restriction" {
      for_each = azurerm_linux_web_app.web.possible_outbound_ip_address_list
      content {
        ip_address = "${ip_restriction.value}/32"
        priority   = index(azurerm_linux_web_app.web.possible_outbound_ip_address_list, ip_restriction.value) + 200
      }
    }
  }
}

dynamic "ip_restriction" で、for_each を使い送信元 IP アドレスのリストをループします。priority では、リストの何番目に値があるかを調べて 200 を足しています。

参考

https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/linux_web_app#possible_outbound_ip_address_list

https://developer.hashicorp.com/terraform/language/expressions/dynamic-blocks

https://developer.hashicorp.com/terraform/language/functions/index_function

Discussion