Accelerate Your Cloud-Native Journey: Deploy an AKS Cluster with Terraform

Danushka Lakmina
7 min readFeb 14, 2023

--

Terraform is a highly acclaimed Infrastructure as Code (IaC) tool that allows for the management and provisioning of infrastructure through code. It utilizes a standardised language for describing and automating the processes of creating, modifying, and deleting infrastructure resources in a controlled, predictable, and secure manner. When it comes to creating an Azure Kubernetes Service (AKS) cluster, Terraform offers several compelling advantages.

One major advantage is reproducibility. With Terraform, you can guarantee that your AKS cluster will be created consistently every time it is run. This makes it effortless to recreate a cluster in case of any failure or to revert back to a previous version if necessary.

Another benefit of Terraform is version control. The Terraform code can be stored in a version control system like Git, which facilitates tracking changes to the infrastructure over time. This makes it easier to work with others, monitor changes, and revert back to a previous version if needed.

Terraform also promotes modularity, allowing the definition of reusable modules that can be shared across teams and projects. This simplifies the management of large-scale AKS clusters and streamlines the process of creating new clusters.

The automation provided by Terraform also helps to make the deployment process of AKS clusters faster and more efficient compared to manual methods. Additionally, Terraform helps to improve security by centralizing and automating the management of security-related configurations such as role-based access control, network security groups, and encryption, reducing the risk of security vulnerabilities and improving the overall security posture of your AKS cluster.

In conclusion, Terraform plays a crucial role in the creation, management, and maintenance of AKS clusters. Its ability to automate the process of creating and modifying infrastructure resources makes it a valuable tool for any organization looking to streamline their AKS deployment process, while ensuring consistency, security, and control.

STEPS:

Under the modules create a folder call AKA or preferred name

In Microsoft Azure, creating a resource group is a recommended best practice that provides a logical container for grouping and managing resources such as virtual machines, storage accounts, and networking components. However, it is not always mandatory to create a resource group for every resource, and certain resources may be created without specifying a resource group.

resourcegroup.tf

resource "azurerm_resource_group" "resource_group" {
name = var.aks_resource_group_name
location = var.location
}

Log Analytics Workspace with Azure AKS provides a comprehensive solution for managing and monitoring your Kubernetes cluster. It allows you to gather log data from your cluster, perform advanced analysis and visualisation, and automate workflows, making it easier to manage and monitor your AKS cluster.

If you want to create a log analytics workspace in Azure using Terraform, you can create a “loganalyticsws.tf” file and define the necessary resources and configurations using Terraform syntax. For example, you may define an Azure resource group, a log analytics workspace, and any necessary settings or features for the workspace.

Note that creating a log analytics workspace requires an Azure subscription and appropriate permissions, and you will need to configure your Terraform environment to authenticate with Azure.

resource "azurerm_log_analytics_workspace" "log_analytics_workspace" {
name = var.log_analytics_workspace_name
location = var.location
resource_group_name = azurerm_resource_group.resource_group.name

}

In Azure, AKS (Azure Kubernetes Service) is a managed service that simplifies the deployment and management of Kubernetes clusters. A fully private AKS cluster refers to a cluster that does not expose any of its Kubernetes API server, worker nodes, or other components to the public internet.

To create a fully private AKS cluster in Azure using Terraform, you can define the necessary resources and configurations in a “aks.tf” file using Terraform syntax. This may include the creation of a virtual network with subnets, a network security group, a private Azure Container Registry (ACR) for container images, and an AKS cluster that is configured to use the private ACR and virtual network.

Note that creating a fully private AKS cluster requires careful consideration of networking and security requirements, and may involve additional configuration such as configuring private DNS zones, using Azure Private Link for API access, and integrating with other Azure services for logging and monitoring.

resource "azurerm_kubernetes_cluster" "aks_cluster" {
name = var.aks_cluster_name
location = var.location
resource_group_name = azurerm_resource_group.resource_group.name
private_cluster_enabled = var.private_cluster_enabled
dns_prefix = var.dns_prefix
kubernetes_version = var.aks_version
sku_tier = var.aks_sku_tier


default_node_pool {
name = var.default_node_pool_name
max_count = var.max_count
min_count = var.min_count
zones = var.availability_zones
vm_size = var.default_vm_size
os_disk_size_gb = var.os_disk_size_gb
enable_auto_scaling = var.enable_auto_scaling
}

key_vault_secrets_provider {
secret_rotation_enabled = var.secret_rotation_enabled
}

oms_agent {
log_analytics_workspace_id = azurerm_log_analytics_workspace.log_analytics_workspace.id
}

service_principal {
client_id = var.client_id
client_secret = var.client_secret
}

tags = {
environment = var.environment
project = var.project
}
}

If you need to create a custom node pool for your AKS (Azure Kubernetes Service) cluster, you can do so by creating a separate Terraform configuration file. The custom node pool can then be referenced within the main Terraform file to include it in the AKS cluster deployment. In order to create this custom node pool, you can use the following nodepool.tf configuration file.

resource "azurerm_kubernetes_cluster_node_pool" "aks_node_pool" {
name = var.nodepool_name
kubernetes_cluster_id = azurerm_kubernetes_cluster.aks_cluster.id
vm_size = var.vm_size
max_count = var.max_count_np
min_count = var.min_count_np
zones = var.availability_zones
enable_auto_scaling = var.enable_auto_scaling
}

To set up an AKS cluster using Terraform, create a dedicated module folder containing the required Terraform files. This folder should contain all resources and configurations necessary to deploy and manage the cluster. Then, run Terraform commands to create and manage the AKS cluster using the definitions specified in the module. This approach ensures consistency and manageability of the AKS cluster.

When using Terraform to manage infrastructure as code in Azure, the state of the managed resources is stored in a “.tfstate” file. This file can contain sensitive information and should be kept secure. To manage the Terraform state file using an Azure Storage Account as a backend configuration, you can follow these steps:

  1. Create an Azure Storage Account to be used as the backend. This can be done using the Azure Portal or the Azure CLI.
  2. In your Terraform configuration file, add the following code block to configure the backend to use the Azure Storage Account:

backend.tf

terraform {
backend "azurerm" {
resource_group_name = "resource-group-name"
storage_account_name = "storageaccountname"
container_name = "tfstate"
key = "terraform.tfstate"
}

}

To properly deploy an AKS (Azure Kubernetes Service) cluster using Terraform, you should ensure that the relevant AKS Terraform configuration files are organized into a dedicated module. Once this module is created, it must be referenced within the main Terraform file to initiate the AKS cluster deployment. This approach ensures that the AKS cluster is deployed with the necessary configuration settings and can be managed and updated efficiently.

To authenticate to an Azure subscription and deploy resources using Terraform, you need to create a service principal, which is a type of application in Azure Active Directory. Once you have created the service principal, you can store its credentials securely in Azure Key Vault. In your Terraform configuration files, you can then reference the service principal ID as “client-sp-id” and the service principal key as “client-sp-secret”, retrieving the values securely from Azure Key Vault. This approach ensures that the service principal credentials are kept secure and can be managed centrally.

main.tf

module "aks" {
source = "../../modules/aks"
aks_resource_group_name = "${var.env}-${var.project}-aks-rg"
location = var.location
log_analytics_workspace_name = "${var.env}-${var.project}-law"
aks_cluster_name = "${var.env}-${var.project}-aks-cluster"
private_cluster_enabled = true
dns_prefix = "${var.env}${var.project}aks"
aks_version = "1.24.9"
aks_sku_tier = "Paid"
default_node_pool_name = "${var.env}salznp0"
default_vm_size = "Standard_D8s_v3"
max_count = 3
min_count = 2
availability_zones = [1, 2, 3]
os_disk_size_gb = 30
enable_auto_scaling = true
secret_rotation_enabled = false
client_id = "${data.azurerm_key_vault_secret.client-sp-id.value}"
client_secret = "${data.azurerm_key_vault_secret.client-sp-secret.value}"
environment = "${var.env}"
project = "${var.project}"
nodepool_name = "${var.env}salznp1"
vm_size = "Standard_D8s_v3"
max_count_np = 3
min_count_np = 2
}

To create an AKS (Azure Kubernetes Service) cluster using Terraform, you can use the following basic commands:

# Initialize Terraform configuration
terraform init

# Preview changes to AKS cluster
terraform plan

# Apply changes to AKS cluster
terraform apply

terraform init is used to initialise your Terraform configuration. This command downloads the required providers and sets up the backend to store your Terraform state.

terraform plan generates an execution plan based on your Terraform configuration, outlining the changes that will be made to your AKS cluster. This allows you to preview the changes and verify that they match your expectations before applying them.

terraform apply takes the execution plan and applies the changes to your AKS cluster, creating, modifying, or deleting resources as necessary. This command makes actual changes to your AKS cluster, so be sure to thoroughly review the changes before running the command.

By using these commands, you can ensure that your AKS cluster is created and managed in a safe, predictable, and version-controlled manner.

Terraform has proven to be a vital tool when it comes to managing and provisioning Azure Kubernetes Service (AKS) clusters. Its automation capabilities, version control support, and improved security make it a valuable asset for organizations looking to streamline their AKS deployment process. With Terraform, you can be confident that your AKS clusters will be created and managed consistently, predictably, and securely, allowing you to concentrate on delivering value to your users. If you’re just starting out with AKS or looking to optimize your existing deployment process, Terraform is definitely a tool to consider.

Thank you for referring to this article. I hope the information I provided will be helpful in your endeavor to create a comprehensive guide on setting up an AKS (Azure Kubernetes Service) cluster using Terraform. If you have any further questions or need additional assistance, please don’t hesitate to ask. I wish you all the best with your article and look forward to reading it when it is completed.

--

--

Danushka Lakmina

Skilled DevOps Engineer with 4+ years of hands-on experience supporting, automating, and optimizing mission critical deployments in AWS, leveraging config.