Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
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:
- Access the current subscription context using azurerm_client_config.
- Create an Azure resource group using azurerm_resource_group.
- Create a Log Analytics workspace for AKS security monitoring data using azurerm_log_analytics_workspace.
- Enable the Defender for Containers plan at the subscription level using azurerm_security_center_subscription_pricing.
- Create an AKS cluster with Azure Policy, OIDC issuer, and Microsoft Defender security monitoring enabled using azurerm_kubernetes_cluster.
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
- Install and configure Terraform.
- Terraform version 1.5.0 or later.
- An Azure account with an active subscription. If you don't have an Azure account, create one for free.
- Azure CLI installed, and signed in using
az login. - Permission to create resource groups, Log Analytics workspaces, and AKS clusters in the target subscription (for example, the Contributor role).
- Permission to modify Microsoft Defender for Cloud pricing plans at the subscription scope. You must be assigned the Security Admin, Owner, or Contributor role on the subscription. For more information, see User roles and permissions in Defender for Cloud.
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.
Create a directory to test the sample Terraform code and set it as the current directory.
Create a file named
main.tfand 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, andSecurityGatingEnabledproperties 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
-upgradeparameter 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 plancommand 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
-outparameter allows you to specify an output file for the plan. Using the-outparameter 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 applycommand assumes you previously ranterraform plan -out main.tfplan. - If you specified a different filename for the
-outparameter, use that same filename in the call toterraform apply. - If you didn't use the
-outparameter, callterraform applywithout any parameters.
Verify the results
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)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 tableThe output shows the
Containersplan with theStandardpricing tier.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 tableThe output lists the
AgentlessVmScanning,ContainerSensor,AgentlessDiscoveryForKubernetes,ContainerRegistriesVulnerabilityAssessments, andContainerIntegrityContributionextensions as enabled.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 jsonThe output shows
azurePolicyandoidcset totrue, and adefenderobject withsecurityMonitoring.enabledset totrueandlogAnalyticsWorkspaceResourceIdset to the ID of the Log Analytics workspace that Terraform created.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 tableThe output shows the workspace name and a
provisioningStateofSucceeded.
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:
Run terraform plan and specify the
destroyflag.terraform plan -destroy -out main.destroy.tfplanKey points:
- The
terraform plancommand 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
-outparameter allows you to specify an output file for the plan. Using the-outparameter ensures that the plan you reviewed is exactly what is applied.
- The
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.