Edit

Share via


Quickstart: Use Terraform to configure Azure Web Application Firewall v2 on Azure Application Gateway

In this quickstart, you use Terraform to create an Azure Application Gateway with an Azure Web Application Firewall (WAF) v2 policy. A key component of creating scalable, reliable, and secure web front ends in Azure, Application Gateway is a web traffic load balancer that helps you to manage traffic to your web applications. Application Gateway bases how it routes traffic on factors that include round-robin, cookie-based sessions, and more. In addition to an Application Gateway, this code also creates a resource group, virtual network, subnet within the virtual network, public IP address, and a WAF policy with custom rules to block traffic from a specific IP address.

Terraform enables the definition, preview, and deployment of cloud infrastructure. Using Terraform, you create configuration files using HCL syntax. The HCL syntax allows you to specify the cloud provider - such as Azure - and the elements that make up your cloud infrastructure. After you create your configuration files, you create an execution plan that allows you to preview your infrastructure changes before they're deployed. Once you verify the changes, you apply the execution plan to deploy the infrastructure.

  • Define the IP address that the WAF custom rule should block.
  • Create an Azure resource group with a unique name.
  • Establish a virtual network with a specific name and address.
  • Generate a random name for the subnet, and create a subnet in the virtual network.
  • Generate a public IP address.
  • Create a WAF policy.
  • Configure settings and define managed rules for the WAF policy.
  • Create a custom rule to block traffic from a specific IP address.
  • Set up the Application Gateway.
  • Configure the SKU and capacity of the Application Gateway.
  • Enable autoscaling for the Application Gateway.
  • Configure the gateway's IP settings.
  • Set up the front-end IP configuration, and define the front-end port.
  • Define the back-end address pool with IP addresses, and configure back-end HTTP settings.
  • Define the HTTP listener.
  • Define the request routing rule.
  • Associate the WAF policy with the Application Gateway.
  • Output the resource group name, public IP address, Application Gateway ID, WAF policy ID, and Application Gateway.

Prerequisites

Implement the Terraform code

The sample code for this article is located in the Azure Terraform GitHub repo. You can view the log file containing the test results from current and previous versions of Terraform. See more articles and sample code showing how to use Terraform to manage Azure resources.

  1. Create a directory in which to test and run the sample Terraform code, and make it the current directory.

  2. Create a file named main.tf, and insert the following code:

    # Create random pet name for resource group
    resource "random_pet" "rg_name" {
      prefix = var.resource_group_name_prefix
    }
    
    # Create resource group
    resource "azurerm_resource_group" "example" {
      location = var.resource_group_location
      name     = random_pet.rg_name.id
    }
    
    # Create a virtual network
    resource "azurerm_virtual_network" "example" {
      name                = "example-vnet"
      address_space       = ["10.0.0.0/16"]
      location            = azurerm_resource_group.example.location
      resource_group_name = azurerm_resource_group.example.name
    }
    
    # Create a subnet within the virtual network
    resource "azurerm_subnet" "example" {
      name                 = "example-subnet"
      resource_group_name  = azurerm_resource_group.example.name
      virtual_network_name = azurerm_virtual_network.example.name
      address_prefixes     = ["10.0.1.0/24"]
    }
    
    # Create a public IP address
    resource "azurerm_public_ip" "example" {
      name                = "example-pip"
      location            = azurerm_resource_group.example.location
      resource_group_name = azurerm_resource_group.example.name
      allocation_method   = "Static"
      sku                 = "Standard"
    }
    
    # Create a Web Application Firewall (WAF) policy
    resource "azurerm_web_application_firewall_policy" "example" {
      name                = "example-waf-policy"
      resource_group_name = azurerm_resource_group.example.name
      location            = azurerm_resource_group.example.location
    
      # Configure the policy settings
      policy_settings {
        enabled                                   = false
        file_upload_limit_in_mb                   = 100
        js_challenge_cookie_expiration_in_minutes = 5
        max_request_body_size_in_kb               = 128
        mode                                      = "Detection"
        request_body_check                        = true
        request_body_inspect_limit_in_kb          = 128
      }
    
      # Define managed rules for the WAF policy
      managed_rules {
        managed_rule_set {
          type    = "OWASP"
          version = "3.2"
        }
      }
    
      # Define a custom rule to block traffic from a specific IP address
      custom_rules {
        name      = "BlockSpecificIP"
        priority  = 1
        rule_type = "MatchRule"
    
        match_conditions {
          match_variables {
            variable_name = "RemoteAddr"
          }
          operator           = "IPMatch"
          negation_condition = false
          match_values       = ["192.168.1.1"] # Replace with the IP address to block
        }
    
        action = "Block"
      }
    }
    
    # Create the Application Gateway
    resource "azurerm_application_gateway" "example" {
      name                = "example-appgw"
      location            = azurerm_resource_group.example.location
      resource_group_name = azurerm_resource_group.example.name
    
      # Configure the SKU and capacity
      sku {
        name = "WAF_v2"
        tier = "WAF_v2"
      }
    
      # Enable autoscaling (optional)
      autoscale_configuration {
        min_capacity = 2
        max_capacity = 10
      }
    
      # Configure the gateway's IP settings
      gateway_ip_configuration {
        name      = "appgw-ip-config"
        subnet_id = azurerm_subnet.example.id
      }
    
      # Configure the frontend IP
      frontend_ip_configuration {
        name                 = "appgw-frontend-ip"
        public_ip_address_id = azurerm_public_ip.example.id
      }
    
      # Define the frontend port
      frontend_port {
        name = "appgw-frontend-port"
        port = 80
      }
    
      # Define the backend address pool with IP addresses
      backend_address_pool {
        name         = "appgw-backend-pool"
        ip_addresses = ["10.0.2.4"] # Replace with your backend IP addresses
      }
    
      # Configure backend HTTP settings
      backend_http_settings {
        name                  = "appgw-backend-http-settings"
        cookie_based_affinity = "Disabled"
        port                  = 80
        protocol              = "Http"
        request_timeout       = 20
      }
    
      # Define the HTTP listener
      http_listener {
        name                           = "appgw-http-listener"
        frontend_ip_configuration_name = "appgw-frontend-ip"
        frontend_port_name             = "appgw-frontend-port"
        protocol                       = "Http"
      }
    
      # Define the request routing rule
      request_routing_rule {
        name                       = "appgw-routing-rule"
        priority                   = 9
        rule_type                  = "Basic"
        http_listener_name         = "appgw-http-listener"
        backend_address_pool_name  = "appgw-backend-pool"
        backend_http_settings_name = "appgw-backend-http-settings"
      }
    
      # Associate the WAF policy with the Application Gateway
      waf_configuration {
        enabled          = true
        firewall_mode    = "Prevention"
        rule_set_type    = "OWASP"
        rule_set_version = "3.2"
      }
    }
    
  3. Create a file named outputs.tf, and insert the following code:

    output "resource_group_name" {
      value = azurerm_resource_group.example
    }
    
    output "public_ip_address" {
      value = azurerm_public_ip.example.ip_address
    }
    
    output "application_gateway_id" {
      value = azurerm_application_gateway.example.id
    }
    
    output "web_application_firewall_policy_id" {
      value = azurerm_web_application_firewall_policy.example.id
    }
    
  4. Create a file named providers.tf, and insert the following code:

    terraform {
      required_providers {
        azurerm = {
          source  = "hashicorp/azurerm"
          version = "~>3.0"
        }
        random = {
          source  = "hashicorp/random"
          version = "~>3.0"
        }
      }
    }
    
    provider "azurerm" {
      features {
        resource_group {
          prevent_deletion_if_contains_resources = false
        }
      }
    }
    
  5. Create a file named variables.tf, and insert the following code:

    variable "resource_group_location" {
      type        = string
      default     = "West Europe"
      description = "Location of the resource group."
    }
    
    variable "resource_group_name_prefix" {
      type        = string
      default     = "rg"
      description = "Prefix of the resource group name that's combined with a random ID so name is unique in your Azure subscription."
    }
    
    variable "blocked_ip_address" {
      type        = string
      default     = ""
      description = "The IP address to be blocked by the WAF custom rule."
    }
    

Important

If you're using the 4.x azurerm provider, you must explicitly specify the Azure subscription ID to authenticate to Azure before running the Terraform commands.

One way to specify the Azure subscription ID without putting it in the providers block is to specify the subscription ID in an environment variable named ARM_SUBSCRIPTION_ID.

For more information, see the Azure provider reference documentation.

Initialize Terraform

Run terraform init to initialize the Terraform deployment. This command downloads the Azure provider required to manage your Azure resources.

terraform init -upgrade

Key points:

  • The -upgrade parameter upgrades the necessary provider plugins to the newest version that complies with the configuration's version constraints.

Create a Terraform execution plan

Run terraform plan to create an execution plan.

terraform plan -out main.tfplan

Key points:

  • The terraform plan command creates an execution plan, but doesn't execute it. Instead, it determines what actions are necessary to create the configuration specified in your configuration files. This pattern allows you to verify whether the execution plan matches your expectations before making any changes to actual resources.
  • The optional -out parameter allows you to specify an output file for the plan. Using the -out parameter ensures that the plan you reviewed is exactly what is applied.

Apply a Terraform execution plan

Run terraform apply to apply the execution plan to your cloud infrastructure.

terraform apply main.tfplan

Key points:

  • The example terraform apply command assumes you previously ran terraform plan -out main.tfplan.
  • If you specified a different filename for the -out parameter, use that same filename in the call to terraform apply.
  • If you didn't use the -out parameter, call terraform apply without any parameters.

Verify the results

  1. Get the Azure resource group name.

    resource_group_name=$(terraform output -raw resource_group_name)
    
  2. Get the public IP address.

    public_ip_address=$(terraform output -raw public_ip_address)
    
  3. Get the WAF policy ID.

    web_application_firewall_policy_id=$(terraform output -raw web_application_firewall_policy_id)
    
  4. Get the Application Gateway ID.

    application_gateway_id=$(terraform output -raw application_gateway_id)
    
  5. Run az network application-gateway show to view the Application Gateway.

    az appservice ase show --name $application_gateway_name --resource-group $resource_group_name  
    

Clean up resources

When you no longer need the resources created via Terraform, do the following steps:

  1. Run terraform plan and specify the destroy flag.

    terraform plan -destroy -out main.destroy.tfplan
    

    Key points:

    • The terraform plan command creates an execution plan, but doesn't execute it. Instead, it determines what actions are necessary to create the configuration specified in your configuration files. This pattern allows you to verify whether the execution plan matches your expectations before making any changes to actual resources.
    • The optional -out parameter allows you to specify an output file for the plan. Using the -out parameter ensures that the plan you reviewed is exactly what is applied.
  2. Run terraform apply to apply the execution plan.

    terraform apply main.destroy.tfplan
    

Troubleshoot Terraform on Azure

Troubleshoot common problems when using Terraform on Azure.