Implementing Azure Kubernetes Service with Terraform

Azure Kubernetes Service (AKS) is a fully managed Kubernetes container orchestration service provided by Microsoft Azure. It enables developers to deploy and manage containerized applications easier and more efficiently. Terraform is an infrastructure as code tool that allows you to define and manage your infrastructure as configuration files. In this tutorial, we will implement AKS with Terraform.

Prerequisites

  • An Azure account
  • Terraform installed on your system
  • Azure CLI installed on your system
  • A basic knowledge of Kubernetes and Terraform

Step 1: Authenticate to Azure

Before we can create resources in Azure, we need to authenticate using the Azure CLI. Open a terminal window and run the following command:

az login

This command will prompt you to open a web browser and authenticate with your Azure account.

Step 2: Create a Resource Group

Next, we will create a resource group in Azure where we will deploy our AKS cluster. Run the following command to create a new resource group:

az group create --name myResourceGroup --location eastus

Replace myResourceGroup with a name of your choice. The --location parameter specifies the region where the resource group will be created.

Step 3: Create an AKS Cluster

We will use Terraform to create our AKS cluster. Start by creating a new directory for your Terraform configuration files. Navigate to this directory in your terminal and create a new file called main.tf.

Add the following code to main.tf:

provider "azurerm" {
  features {}
}

resource "azurerm_kubernetes_cluster" "aks" {
  name                = "myAKSCluster"
  location            = "eastus"
  resource_group_name = "myResourceGroup"
  dns_prefix          = "myakscluster"

  linux_profile {
    admin_username = "azureuser"

    ssh_key {
      key_data = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCdQiq8+Nez8Kwj4C+cn1evFF/4xjiTpIrlb1gbv9e8ssCdIP/mD0Tg+HpaJG/UHPFdOeqD+vq4QY92zNH60hzGgZI/7UQsNfYJlVdVX888JAv6wPhK3v3aMzJZU6zYkD0H0XjNNYDbMYAYG+Ob080XMGk2N2Cux7RhtkwSm+aT//OR1nqGIZ22bbh45anK0JOWyPlp8Gi2T7fy42JeuV/lmtq8e5VYMhJTvJbO0qM27edSm5rGpo2X416rTAnb40msT/TVRAOr5GoMp2UuJp5wE2//nP2WgwVZ0gqQHKNb4OCQzjPFEv/H9D+mJtOxKq8mRpfwQA5CfPeYx root@ubuntu"
    }
  }

  service_principal {
    client_id     = "YOUR_APP_ID"
    client_secret = "YOUR_APP_PASSWORD"
  }

  agent_pool_profile {
    name            = "default"
    count           = 1
    vm_size         = "Standard_DS2_v2"
    os_type         = "Linux"
    os_disk_size_gb = 30
  }

  tags = {
    Environment = "dev"
  }
}

This code creates a new AKS cluster in your Azure account. Replace myAKSCluster with a name of your choice.

The service_principal block defines the Azure Active Directory (AD) service principal used to manage the AKS cluster. Replace the placeholders YOUR_APP_ID and YOUR_APP_PASSWORD with the ID and password of your service principal. Refer to Azure documentation for details on creating a service principal.

Step 4: Initialize and Apply Terraform Configuration

Initialize Terraform in the directory with the following command:

terraform init

This will download the required modules and providers. Then, apply the Terraform configuration with the following command:

terraform apply

This command will prompt you for confirmation before applying the configuration. Type yes to confirm and begin the deployment process.

After a few minutes, Terraform will have created your AKS cluster in Azure.

Step 5: Configure Kubernetes

Now that our AKS cluster is up and running, we need to configure our Kubernetes command line tool (kubectl) to use it. Start by downloading the Kubernetes configuration file for your AKS cluster with the following command:

az aks get-credentials --name myAKSCluster --resource-group myResourceGroup

This command downloads the AKS-specific Kubernetes configuration file and adds it to your default Kubernetes configuration file (~/.kube/config) so that kubectl can access your AKS cluster.

Verify that you can connect to your AKS cluster with the following command:

kubectl get nodes

This command should return a list of nodes in your AKS cluster.

Step 6: Create a Deployment

We will now create a simple deployment to test our AKS cluster. Create a new file called deployment.yaml in your Terraform directory and add the following code:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 3
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:latest
        ports:
        - containerPort: 80

This code defines a deployment with 3 replicas of the latest version of the nginx image.

Apply the deployment to your AKS cluster with the following command:

kubectl apply -f deployment.yaml

This command creates the deployment and its associated objects (replica sets and pods) in your AKS cluster.

Step 7: Expose the Deployment

We will now expose the deployment to the internet by creating a service. Create a new file called service.yaml in your Terraform directory and add the following code:

apiVersion: v1
kind: Service
metadata:
  name: nginx-service
spec:
  selector:
    app: nginx
  ports:
    - name: http
      protocol: TCP
      port: 80
      targetPort: 80
  type: LoadBalancer

This code defines a load balancer service for our nginx deployment.

Apply the service to your AKS cluster with the following command:

kubectl apply -f service.yaml

This command creates the service and a public IP address in your AKS cluster.

Step 8: Verify the Deployment

To verify that our deployment is working correctly and accessible from the internet, we need to obtain the public IP address of our load balancer service. Use the following command to get the IP address:

kubectl get services

This command should return a list of services in your AKS cluster.

Look for the EXTERNAL-IP column for your nginx-service. If the IP address is shown as <pending>, wait a minute and try the command again.

Once you have the IP address, test the deployment by opening a web browser and navigating to http://<IP-ADDRESS>. You should see the default nginx welcome page.

Conclusion

In this tutorial, we have seen how to create an AKS cluster with Terraform, configure Kubernetes to use the cluster, and deploy a simple application. This should give you a good starting point for using AKS and Terraform to manage your containerized applications in Azure. Remember to delete your AKS cluster and associated resources when you are done to avoid incurring unnecessary costs.

Related Post