[Webinar] Policy-as-Code for Secure, Resilient Infrastructure

➡️ Register Now

Azure

How to Provision Azure AKS Cluster Using Terraform

154.terraform aks

Subscribe to our Newsletter

Mission Infrastructure newsletter is a monthly digest of the latest posts from our blog, curated to give you the insights you need to advance your infrastructure game.

What is AKS?

Azure Kubernetes Service (AKS) is a managed container orchestration service provided by Microsoft Azure. It simplifies the deployment, management, and scaling of Kubernetes clusters in the cloud, enabling developers to focus on building and deploying applications without having to handle the complexities of Kubernetes infrastructure.

AKS integrates with a range of Azure services, including Azure Monitor for centralized monitoring, Azure Security Center for security management, and Azure Application Gateway for load balancing. These integrations support efficient monitoring, security, and traffic management for applications running on AKS. 

AKS also works with Azure Container Registry (ACR) to simplify the storage, retrieval, and management of Docker images, enhancing workflow efficiency for containerized applications.

Why should you use Terraform with AKS?

Using Terraform to manage AKS  allows for version-controlled definitions of AKS clusters and their resources, facilitating team collaboration and change tracking. 

 

Terraform’s declarative configuration simplifies cloud environment management, and its ecosystem integration streamlines workflows across Azure services.  By automating AKS deployments with Terraform, teams can efficiently manage cluster configurations, scale resources on-demand, and apply updates or rollbacks with minimal downtime, enhancing operational efficiency and reliability.

Prerequisites for deploying AKS cluster in Terraform

The simplest way to provision an AKS cluster using Terraform is to call the official azurerm registry module. This allows you to create a group with just four lines of code (assuming you accept all the defaults)!

A module is simply a collection of .tf configuration files that define multiple related resources, coded to enable code reuse. These files are held in a folder.

The Terraform registry has a huge collection of ready-to-use modules, saving you the time and effort of coding for common tasks. For example, you can call the Azure VM module from the public registry instead of defining code for creating a VM in Azure.

There are downsides to using registry modules, rather than creating and maintaining your own module or alternatively creating the individual resources in your Terraform code. Public modules can be less flexible because you don’t have direct control over the module code. This is why enterprises generally use modules created by the enterprise. However, they are a good option for testing, and well-maintained public modules can still be a great option for production scenarios.

How to create an AKS cluster with Terraform

Make sure you have installed:

  • Azure CLI
  • Terraform
  • kubectl

1. Create the main.tf file

Create a directory for your Terraform configuration files. In this directory, create a file called main.tf that will include our azurerm provider and the module. 

Paste the code below:

terraform {
  required_providers {
    azurerm = {
      source = "hashicorp/azurerm"
      version = "3.40.0"
    }
  }
}

provider "azurerm" {
   features {}
}

module "aks_example_named_cluster" {
  source  = "Azure/aks/azurerm//examples/named_cluster"
  version = "6.2.0"
}

2. Set up Azure

To connect to Azure, first, create an Azure Account and log in to it the command line:

Then, select your subscription:

3. Run Terraform

Run through the usual Terraform workflow commands from the directory your main.tf file is in.

Initialize the Terraform configuration with terraform init:

terraform init terraform aks

Review the configuration with terraform plan.

And apply the configuration to create the AKS cluster:

terraform apply terraform aks

When prompted, confirm the changes. Now, Terraform will provision the AKS cluster in Azure, which may take a few minutes.

terraform aks cluster

4. Configure kubectl to connect to the AKS cluster

Once the AKS cluster is created, use the Azure CLI to configure kubectl:

az aks get-credentials --resource-group <your-resource-group-name> --name <your-aks-cluster-name>

Now you should be able to interact with your AKS cluster using kubectl. You can, for example, run:

kubectl get nodes

5. Explore the Azure portal

In the Azure portal, you should see a resource group with a randomly created name containing seven resources, as shown below:

terraform aks azure portal

The module created both the AKS cluster and the supporting services required for its secure operation, including a disk encryption set, key vault, log analytics workspace, container insights solution, and managed identity. It also created the virtual network to which the AKS cluster is attached.

This is great for quickly spinning up an AKS cluster for test purposes. However, in the real world, you’ll need to tailor the deployment to work in your environment.

  • For example, most Azure environments will probably want to hook into and reuse an existing key vault, log analytics workspace, and virtual network.
  • You will also likely need to adhere to a defined naming format rather than the randomly created names for the key vault, managed identity, and virtual network shown above.
  • You might also want to amend the outputs so you can use the values in other parts of your Terraform configuration.
  • You may want to tailor the deployment to adhere to specific policies to harden and secure your AKS deployment.

Despite the extensive configuration required, once created, it gives you more flexibility and control over the code — and more code to maintain.

6. Clean up

When you’re finished, you can remove all resources with:

terraform destroy

This will remove the AKS cluster and all other resources defined in your Terraform configuration.

Diving into the Terraform AKS module

Let’s examine the defaults in the registry module source code and explore the available options. The module’s GitHub source code is linked from the Terraform registry page.

The available inputs and outputs are listed on the README page. When set, these allow you to customize your deployment. As with all modules, they are also listed on the Terraform registry page.

The module providers are listed in the dependencies tab. They are downloaded and installed automatically upon terraform init.

To adhere to recommended security settings when deploying an AKS cluster, the module sets some recommended defaults from the Azure policies section at Bridgecrew by Prisma Cloud, such as ensuring AKS uses a disk encryption set. You can check out their recommendations for your cluster here.

AKS Terraform registry module custom configuration example

To demonstrate how to use the registry module with some custom values, we will run through an example configuration.

On the Terraform registry page, you will notice two required inputs, prefix and resource_group_name. These will need to be defined.

We’ll add a prefix of “test” and import a resource group I previously created called “aks-test-rg”.

terraform aks resource group
terraform {
  required_providers {
    azurerm = {
      source = "hashicorp/azurerm"
      version = "3.40.0"
    }
  }
}

provider "azurerm" {
   features {}
}

module "aks_example_named_cluster" {
  source              = "Azure/aks/azurerm/"
  version             = "6.2.0"
  prefix              = "test"
  resource_group_name = "aks-test-rg"
}

From the available optional values, we will set the admin_usernameto “testaksadmin”.

terraform aks admin username

Turn on the Azure Policy Addon:

terraform aks Azure Policy Addon

Then, link your AKS cluster to the previously created log analytics workspace by setting cluster_log_analytics_workspace_name to “test-aks-law”.

terraform aks Azure Policy Addon
terraform aks workspace name

Set the cluster name to adhere to our naming convention by setting cluster_name to “jr-test-aks”.

terraform aks cluster name
terraform aks ingress name

Define the location of your cluster as “uksouth”.

terraform aks cluster location

Set the log_retention_in_days to “365” days:

terraform aks cluster retention

Our code now looks like this:

terraform {
  required_providers {
    azurerm = {
      source = "hashicorp/azurerm"
      version = "3.40.0"
    }
  }
}

provider "azurerm" {
   features {}
}

module "aks_example_named_cluster" {
  source                               = "Azure/aks/azurerm"
  version                              = "6.2.0"
  prefix                               = "test"
  resource_group_name                  = "aks-test-rg"
  admin_username                       = "testaksadmin"
  azure_policy_enabled                 = true
  cluster_log_analytics_workspace_name = "test-aks-law"
  cluster_name                         = "jr-test-aks"
  location                             = "uksouth"
  log_retention_in_days                = "365"
}

Run terraform init (make sure you have the latest Terraform version! by typing terraform version to avoid unexpected errors!)

terraform init provider terraform aks
terraform plan terraform aks

Many other options and outputs are available for you to tailor your AKS deployment to your requirements.

terraform destroy terraform aks

You can use Spacelift to help you manage the complexities and compliance challenges of Terraform. It brings with it a GitOps flow, so your infrastructure repository is synced with your Terraform Stacks, and pull requests show you a preview of what they’re planning to change. It also has an extensive selection of policies, which lets you automate compliance checks and build complex multi-stack workflows. 

 

If you want to learn more about what you can do with Spacelift, check out this article, create a free trial account, or book a demo with one of our engineers.

Key points

Using the official azurerm AKS Terraform public registry module is the fastest and arguably easiest way to create a Kubernetes cluster on Azure. You can customize your deployment as required by adding inputs and outputs to your configuration, as shown in the example above.

However, creating and maintaining your own AKS module or configuration may be preferable for flexibility and full control over the code.

Note: New versions of Terraform are placed under the BUSL license, but everything created before version 1.5.x stays open-source. OpenTofu is an open-source version of Terraform that expands on Terraform’s existing concepts and offerings. It is a viable alternative to HashiCorp’s Terraform, being forked from Terraform version 1.5.6.

Manage Terraform better and faster

If you are struggling with Terraform automation and management, check out Spacelift. It helps you manage Terraform state, build more complex workflows, and adds several must-have capabilities for end-to-end infrastructure management.

Start free trial

The Practitioner’s Guide to Scaling Infrastructure as Code

Transform your IaC management to scale

securely, efficiently, and productively

into the future.

ebook global banner
Share your data and download the guide