Edit

Quickstart: Use Terraform for Defender for Containers on Azure

Microsoft Defender for Containers is a cloud workload protection plan in Microsoft Defender for Cloud that provides security monitoring, vulnerability assessment, and threat detection for your Kubernetes environments. In this quickstart, you use Terraform to enable the Defender for Containers plan at the subscription level and deploy an Azure Kubernetes Service (AKS) cluster with Microsoft Defender security monitoring connected to a Log Analytics workspace.

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.

In this article, you learn how to:

Important

The azurerm_security_center_subscription_pricing resource sets the Defender for Containers plan for the entire Azure subscription, not just the AKS cluster created in this quickstart. Enabling the Standard tier affects all supported container resources in the subscription, including other AKS clusters and container registries, and can increase your Azure bill. Review the Defender for Containers pricing before you apply this configuration in a subscription that you share with other workloads.

Prerequisites

Implement the Terraform code

Note

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 to test the sample Terraform code and set it as the current directory.

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

    terraform {
      required_version = ">= 1.5.0"
    
      required_providers {
        azurerm = {
          source  = "hashicorp/azurerm"
          version = "~> 4.0"
        }
      }
    }
    
    provider "azurerm" {
      features {}
    }
    
    data "azurerm_client_config" "current" {}
    
    locals {
      suffix   = substr(replace(data.azurerm_client_config.current.subscription_id, "-", ""), 0, 6)
      location = "eastus"
    }
    
    resource "azurerm_resource_group" "example" {
      name     = "rg-aks-defender-${local.suffix}"
      location = local.location
    }
    
    resource "azurerm_log_analytics_workspace" "example" {
      name                = "law-aks-defender-${local.suffix}"
      location            = azurerm_resource_group.example.location
      resource_group_name = azurerm_resource_group.example.name
      sku                 = "PerGB2018"
      retention_in_days   = 30
    }
    
    resource "azurerm_security_center_subscription_pricing" "containers" {
      tier          = "Standard"
      resource_type = "Containers"
    
      extension {
        name = "AgentlessVmScanning"
        additional_extension_properties = {
          ExclusionTags = jsonencode([])
        }
      }
    
      extension {
        name = "ContainerSensor"
        additional_extension_properties = {
          AntiMalwareEnabled    = "True"
          AutoProvisioning      = "True"
          InstallationMethod    = "AKSAddon"
          SecurityGatingEnabled = "True"
        }
      }
    
      extension {
        name = "AgentlessDiscoveryForKubernetes"
      }
    
      extension {
        name = "ContainerRegistriesVulnerabilityAssessments"
      }
    
      extension {
        name = "ContainerIntegrityContribution"
      }
    }
    
    resource "azurerm_kubernetes_cluster" "example" {
      name                              = "aks-defender-${local.suffix}"
      location                          = azurerm_resource_group.example.location
      resource_group_name               = azurerm_resource_group.example.name
      dns_prefix                        = "aks-defender-${local.suffix}"
      role_based_access_control_enabled = true
      azure_policy_enabled              = true
      oidc_issuer_enabled               = true
    
      default_node_pool {
        name       = "system"
        node_count = 1
        vm_size    = "Standard_D2s_v3"
    
        upgrade_settings {
          drain_timeout_in_minutes      = 0
          max_surge                     = "10%"
          node_soak_duration_in_minutes = 0
        }
      }
    
      identity {
        type = "SystemAssigned"
      }
    
      microsoft_defender {
        log_analytics_workspace_id = azurerm_log_analytics_workspace.example.id
      }
    
      tags = {
        Environment = "Test"
        Purpose     = "DefenderForContainers"
      }
    
      depends_on = [
        azurerm_security_center_subscription_pricing.containers
      ]
    }
    
    output "resource_group_name" {
      value = azurerm_resource_group.example.name
    }
    
    output "aks_cluster_name" {
      value = azurerm_kubernetes_cluster.example.name
    }
    
    output "log_analytics_workspace_id" {
      value = azurerm_log_analytics_workspace.example.id
    }
    

Note

The configuration enables the following Defender for Containers extensions on the Containers pricing plan:

  • AgentlessVmScanning: Performs agentless vulnerability scanning of AKS node disks without installing an agent on the nodes.
  • ContainerSensor: Deploys the Defender sensor to AKS nodes. The AntiMalwareEnabled, AutoProvisioning, InstallationMethod, and SecurityGatingEnabled properties enable malware protection, automatic provisioning of the sensor, installation through the AKS security profile add-on, and security gating for the sensor.
  • AgentlessDiscoveryForKubernetes: Discovers Kubernetes cluster configuration and workload data without requiring an agent.
  • ContainerRegistriesVulnerabilityAssessments: Scans container images in Azure Container Registry for known vulnerabilities.
  • ContainerIntegrityContribution: Monitors runtime configuration drift and integrity of running containers.

The AKS cluster resource also enables Azure Policy (azure_policy_enabled) for at-scale governance of the cluster, the OIDC issuer (oidc_issuer_enabled) for workload identity federation, and the Microsoft Defender security profile (microsoft_defender) that connects the cluster to the Log Analytics workspace for security monitoring.

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 resource group name, AKS cluster name, and Log Analytics workspace ID from the Terraform state.

    resource_group_name=$(terraform output -raw resource_group_name)
    aks_cluster_name=$(terraform output -raw aks_cluster_name)
    log_analytics_workspace_id=$(terraform output -raw log_analytics_workspace_id)
    
  2. Verify that the Defender for Containers plan is set to the Standard tier at the subscription level by using the az security pricing show command.

    az security pricing show -n Containers --query "{name:name, tier:pricingTier}" -o table
    

    The output shows the Containers plan with the Standard pricing tier.

  3. Check the extensions enabled on the plan by using the az security pricing show command.

    az security pricing show -n Containers --query "extensions[].{name:name, isEnabled:isEnabled}" -o table
    

    The output lists the AgentlessVmScanning, ContainerSensor, AgentlessDiscoveryForKubernetes, ContainerRegistriesVulnerabilityAssessments, and ContainerIntegrityContribution extensions as enabled.

  4. Confirm that Azure Policy, the OIDC issuer, and Microsoft Defender security monitoring are enabled on the AKS cluster by using the az aks show command.

    az aks show \
      --resource-group $resource_group_name \
      --name $aks_cluster_name \
      --query "{azurePolicy:addonProfiles.azurepolicy.enabled, oidc:oidcIssuerProfile.enabled, defender:securityProfile.defender}" \
      -o json
    

    The output shows azurePolicy and oidc set to true, and a defender object with securityMonitoring.enabled set to true and logAnalyticsWorkspaceResourceId set to the ID of the Log Analytics workspace that Terraform created.

  5. Confirm that the Log Analytics workspace exists and is linked to the AKS cluster by using the az monitor log-analytics workspace show command.

    az monitor log-analytics workspace show --ids $log_analytics_workspace_id --query "{name:name, provisioningState:provisioningState}" -o table
    

    The output shows the workspace name and a provisioningState of Succeeded.

Clean up resources

Important

The azurerm_security_center_subscription_pricing resource manages the Defender for Containers plan for the entire subscription. When Terraform destroys this resource, it resets the Containers pricing tier back to Free for the whole subscription. This action disables Defender for Containers protection and its extensions for every AKS cluster and container registry in that subscription, not only the resources created in this quickstart. Confirm that no other clusters or workloads in the subscription depend on Defender for Containers protection before you continue.

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.

Next step