How to Set Up an Azure Kubernetes Service Cluster with Terraform
Published: 2023-07-19 09:31:01

[Azure Kubernetes Service](https://azure.microsoft.com/en-us/free/kubernetes-service/) (AKS) is a fully managed container orchestration service provided by Microsoft Azure. AKS is a Kubernetes Cluster platform that hosts deployed cloud-native Kubernetes applications. It offers automatic management and scaling of containerized applications. 

In this tutorial, you will learn how to set up an Azure Kubernetes Service Cluster with Terraform. Let's get started!

### What is Terraform?
[Terraform](https://www.terraform.io/) is an open-source infrastructure as a code tool. It is designed by [HashiCorp](https://www.hashicorp.com/) and written in Go Programming Language. Terraform is used to automate the creation of DevOps infrastructure and tasks. Terraform provisions and configures your DevOps infrastructure. It spins up new servers, creates load balancers, and node groups, and performs network configurations. Terraform is mostly applied to provision resources on cloud providers like AWS, Google Cloud, and Microsoft Azure. It can automate and provision infrastructure on any cloud platform. We will use Terraform to set up an Azure Kubernetes Service Cluster that has all the necessary cloud resources.

[Infrastructure as code](https://en.wikipedia.org/wiki/Infrastructure_as_code) (IaC) allow the DevOps team to create all their infrastructure using configuration files and scripts rather than using a command line interface tool or graphical user interface. In Terraform you can use the [HashiCorp Configuration Language](https://developer.hashicorp.com/terraform/language/syntax/configuration) to write your configuration files and scripts. The Terraform files are declarative and human-readable. Lets install Terraform.

#### Installing Terraform on Windows
To Installing Terraform on Windows, run this command on your Windows terminal:

```choco
choco install terraform
```

#### Installing Terraform on macOs
To Installing Terraform on macOs, run these commands on your macOS terminal:

```choco
brew tap hashicorp/tap
brew install hashicorp/tap/terraform
```

#### Installing Terraform on Linux
To Installing Terraform on Linux, run this command on your Linux terminal:

```choco
sudo apt-get install terraform
```

### Verifying Terraform Installation
To verify Terraform installation, run this command:

```terraform
terraform -help
```
If Terraform was installed successfully, it will list all the available Terraform commands.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gt10wpqhkyeb77d1kh1y.png)

If you the commands then Terraform is working. Let's now create a Microsoft Azure free account.

### Create a Microsoft Azure Free Account
Before we set up an Azure Kubernetes Service Cluster with Terraform, you need a Microsoft Azure account. In this tutorial, we will sign up for a Microsoft Azure free account. All the AKS Cluster resources and services that Terraform will provision will be covered in the Microsoft Azure free plan or subscription. 

To create a Microsoft Azure free account, follow this [link](https://azure.microsoft.com/en-us/free/). You will use your Microsoft account to sign up for a Microsoft Azure free account. You will then follow the instructions to verify your phone number and credit/debit card details. After creating the Microsoft Azure free account, Microsoft will give you a $200 credit for you to use in the first 30 days. The next step is to install the Azure CLI.

### Installing Azure CLI
Azure CLI is the command line interface tool that allows Azure users to access their Microsoft Azure account from the terminal. They will use Azure CLI commands to manage their Azure account and resources. 

#### Install the Azure CLI on Linux
To install the Azure CLI on Linux, run the following `sudo` command:

```sudo
sudo apt-get install azure-cli
```
#### Install Azure CLI on macOS
To install Azure CLI on macOS, run the following `brew` command:

```brew
brew install azure-cli
```
Let's login into the Microsoft Azure account using the Azure CLI.

### Login into the Microsoft Azure Account using the Azure CLI
To login into the Microsoft Azure account using the Azure CLI, run this Azure command:

```az
az login
```
After executing the command above, Azure CLI will open your default web browser where you will input your credentials for the Microsoft Azure account. After logging in to your Microsoft Azure account, you can run Azure CLI commands against your Microsoft Azure default subscription. The next step is to install Kubectl using the Azure CLI.

### Installing Kubectl using the Azure CLI
[Kubectl](https://kubernetes.io/docs/tasks/tools/) is a command line interface tool for accessing any Kubernetes cluster. We will use Kubectl to access the AKS Cluster that Terraform will provision. Kubectl will access the AKS resource groups, node groups, Kubernetes Deployments, and Services.

To install Kubectl, run this Azure command:

```az
az aks install-cli
```
You should now have a Microsoft Azure Free Account, a Terraform CLI, Azure CLI, and Kubectl. Let's now set up an Azure Kubernetes Service Cluster with Terraform.

### Set up an Azure Kubernetes Service Cluster with Terraform
We will use Terraform to set up an AKS cluster with 2 nodes and an Azure resource group. We will create Terraform files to provision the AKS cluster with 2 nodes and an Azure resource group. We will also create a Terraform file to specify the Terraform Provider that Terraform will use to interact with Microsoft Azure.

A [Terraform Provider](https://registry.terraform.io/browse/providers) is an inbuilt plugin that enables Terraform to interact with third-party APIs and Cloud Providers (Google Cloud, AWS, and Microsoft Azure) and other APIs. From the [official Terraform Provider registry](https://registry.terraform.io/browse/providers), Terraform supports 130 providers.

There are different Terraform Providers that enable Terraform to interact with Microsoft Azure. The most common one are [Azure Stack](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs), [AzureDevops](https://registry.terraform.io/providers/microsoft/azuredevops/latest/docs), [AzureRM](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs), [AzAPI](https://registry.terraform.io/providers/Azure/azapi/latest/docs) and [AzureAD.](https://registry.terraform.io/providers/hashicorp/azuread/latest/docs). In this tutorial, we use the AzureRM Terraform Provider. Let's create a Terraform file for the AzureRM Terraform Provider.

### Create a Terraform file for the AzureRM Terraform Provider
In your computer, create a folder named `terraform-aks`. In the `terraform-aks` folder, create a new file named `providers.tf`. Open the file and add the following HashiCorp Configuration Language code:

```terraform
provider "azurerm" {
  features {}
}

terraform {
  required_providers {
    azurerm = {
      source = "hashicorp/azurerm"
      version = "2.78.0"
    }
  }
}
```
Terraform will use the `azurerm` Terraform Provider. It will enable Terraform to create and provision an AKS cluster. The next step is to create a variables.tf file.

### Create a variables.tf File
In the `terraform-aks` folder, create a new file named `variables.tf`. Open the file and add the following HashiCorp Configuration Language code:

```terraform
variable "resource_group_name" {
  type        = string
  description = "Resource Group name in Microsoft Azure"
}

variable "location" {
  type        = string
  description = "Resources location in Microsoft Azure"
}

variable "cluster_name" {
  type        = string
  description = "AKS name in Microsoft Azure"
}

variable "kubernetes_version" {
  type        = string
  description = "Kubernetes version"
}

variable "system_node_count" {
  type        = number
  description = "Number of AKS worker nodes"
}

variable "node_resource_group" {
  type        = string
  description = "Resource Group name for cluster resources in Microsoft Azure"
}
```
This file defines all the variables that our main Terraform file will use. The next step is to create a terraform.tfvars file.

### Create a terraform.tfvars File
In the `terraform-aks` folder, create a new file named `terraform.tfvars`. Open the file and add the following HashiCorp Configuration Language code:

```terraform
resource_group_name = "aks_terraform_rg"
location            = "East Us"
cluster_name        = "aks-terraform-cluster"
kubernetes_version  = "1.24.6"
system_node_count   = 2
node_resource_group = "aks_terraform_-node_resources_rg"
```
This file contains the actual values of the variables defined in the variables.tf file. The next step is to create a main.tf file.

### Create a main.tf  file
In the `terraform-aks` folder, create a new file named `main.tf `. Open the file and add the following HashiCorp Configuration Language code:

```terraform
resource "azurerm_resource_group" "rg" {
  name     = var.resource_group_name
  location = var.location
}

resource "azurerm_kubernetes_cluster" "aks" {
  name                = var.cluster_name
  kubernetes_version  = var.kubernetes_version
  location            = var.location
  resource_group_name = azurerm_resource_group.rg.name
  dns_prefix          = var.cluster_name
  node_resource_group = var.node_resource_group

  default_node_pool {
    name                = "system"
    node_count          = var.system_node_count
    vm_size             = "Standard_DS2_v2"
    type                = "VirtualMachineScaleSets"
    availability_zones  = [1, 2, 3]
    enable_auto_scaling = false
  }

  identity {
    type = "SystemAssigned"
  }

  network_profile {
    load_balancer_sku = "Standard"
    network_plugin    = "kubenet" # azure (CNI)
  }
}
```
This file will define all our Terraform resources for the infrastructure. Terraform will use this file to provision the AKS cluster. In this file, you use Terraform resource blocks to define the resources of your Terraform infrastructure. You can add as many resource blocks as you want in this file. Here, we have only two resource blocks for creating the `azurerm_resource_group` resource group and the `azurerm_kubernetes_cluster` AKS cluster. 

The next step is to create an output.tf file.

### Create an output.tf file
In the `terraform-aks` folder, create a new file named `output.tf `. Open the file and add the following HashiCorp Configuration Language code:

```terraform
output "aks_id" {
  value = azurerm_kubernetes_cluster.aks.id
}

output "aks_fqdn" {
  value = azurerm_kubernetes_cluster.aks.fqdn
}

output "aks_node_rg" {
  value = azurerm_kubernetes_cluster.aks.node_resource_group
}
```
This file will specify the output to be displayed in the console after creating the AKS cluster with Terraform commands. Terraform will output the AKS Cluster ID (aks_id), AKS Cluster name (aks_fqdn), and the resource group name (aks_node_rg). Let's now start applying the Terraform commands.

### Applying the Terraform init command
This comamnd will initilaze Terraform and download the `azurerm` Terraform Provider:

```terraform
terraform init
```
The Terraform command will output the following:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t6albwnmrcab8kk7xvll.png)

### Applying the Terraform plan command
This command will scan the main.tf file and determine the resources that Terraform will provision:

```terraform
terraform plan
```
The Terraform command will display the following outputs:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s2v4ym0ivb77hmxx0new.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9urwjr3xsk25d9dfsl4p.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wxlthlmcfotx7vu55iyj.png)

From the outputs, Terraform will provision two resources.

### Applying the Terraform apply command
This command will provision the two resources and apply them in the AKS cluster:

```terraform
terraform apply
```
When you run the command, you will be prompted to confirm if you want to provision the two resources. Type `yes` to continue the process:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z7reknhrd90fyzwg9vby.png)

It will take a few minutes for Terraform to provision the two resources. Upon completion, Terraform will display the resources added and the outputs defined in the output.tf file.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s8m2ffkt49eezb1og1ae.png)

From the image, Terraform has provisioned the two resources and displayed the outputs defined in the output.tf file. Let's login into the Azure Portal to view the provisioned resources.

### Login into the Azure Portal
After logging in to the Azure Portal, click `All resources`:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bytma1qe1w2f7xo5d8sz.png)
It will display all the resources provisioned:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fo3qw8lgha2mcv0f0pr2.png)

You will then click `aks-terraform-cluster`:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tts7enguv23exjj2ev55.png)

It will display the Kubernetes resource in our AKs cluster:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/loqfigcrmum2wp4nwu0g.png)

We have successfully set up an Azure Kubernetes Service Cluster with Terraform. If you want to delete these resources, run the following Terraform command:

```terraform
terrorm destroy
```
You will then input `Yes` when prompted:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/053qwfhf5ahldg1r0pw5.png)

Terraform will destroy the two resources:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2bzpgz3pakbv20q5iozg.png)

### Conclusion
In this tutorial, we have learned how to set up an Azure Kubernetes Service Cluster with Terraform. We installed Terraform on Windows, Linux, and macOS. Before we started setting up an Azure Kubernetes Service Cluster with Terraform, we created a Microsoft Azure account. After this, we install the Azure CLI on Linux, Windows, and macOS. We then logged in to the Microsoft Azure Account and installed Kubectl using the Azure CLI. 

In the next steps, we created Terraform files for provisioning the AKS cluster with 2 nodes and an Azure resource group. Finally, we applied the Terraform init, plan, and apply commands. The commands provided an AKS cluster and the resource group. Using this tutorial, you can successfully set up an Azure Kubernetes Service Cluster with Terraform.