Terraform EKS Module - Provision EKS Cluster with in <30 minutes

Tasrie IT Services

Tasrie IT Services

·7 min read
Terraform EKS Module - Provision EKS Cluster with in <30 minutes

Introduction

When it comes to deploying applications on Amazon Web Services (AWS), the Elastic Kubernetes Service (EKS) has emerged as a popular choice thanks to its ability to automate the deployment, scaling, and management of containerized applications. However, setting up an EKS cluster can be time-consuming and complex without a proper tool. This is where the Terraform EKS Module comes in. In this essay, we will explore we will launch latest version of EKS version 1.27 by leveraging the Terraform EKS Module to provision an EKS cluster in less than 30 minutes.

What is Terraform?

Terraform is a popular open-source infrastructure-as-code tool from HashiCorp that allows users to define, provision, and manage infrastructure resources across multiple cloud providers (e.g. AWS, Azure, Google Cloud). With Terraform, users can express their infrastructure as code in a declarative language, making it easier to version control and collaborate.

What is EKS?

Elastic Kubernetes Service (EKS) is a fully managed Kubernetes service from AWS that allows users to easily deploy, scale, and manage containerized applications. EKS is built on Kubernetes, the popular open-source container orchestration platform, and integrates with other AWS services like Elastic Load Balancing (ELB) and AWS Identity and Access Management (IAM).

Why is EKS important?

EKS simplifies the process of deploying containerized applications by providing a scalable, secure, and highly available platform for running container workloads. EKS can also help reduce operational overhead by automating tasks such as patching, scaling, and monitoring of Kubernetes clusters.

Setting Up the Environment

To set up the environment for provisioning an EKS cluster using the Terraform EKS Module, we need to perform several steps:

Installing Terraform

Install Terraform on your local machine by downloading the appropriate Terraform binary and adding it to your system path.

Acquiring AWS Credentials

Create an AWS account or use an existing one, then generate an access key and secret key pair in the AWS console. Save these credentials in a secure location.

Creating an IAM User for Terraform

Create an IAM user in the AWS console with the necessary permissions to provision EKS resources, then attach an appropriate policy to the user.

Obtaining the Terraform EKS Module

In this tutorial we will use this module officially from AWS. This example will the create following EKS resources.

  • EKS Cluster

  • managed node_group

  • add-ons

    • AWS CNI

    • kube-proxy

    • core-dns

  • access to two IAM users.

https://registry.terraform.io/modules/terraform-aws-modules/eks/aws/latest

Creating the Terraform EKS Configuration

Create a new Terraform configuration file main.tf and copy the contents below.

In this example we will launch the latest version as of today is 1.27

hcl
module "eks" {
  source  = "terraform-aws-modules/eks/aws"
  version = "~> 19.0"

  cluster_name    = "tasrie-eks-cluster"
  cluster_version = "1.27"

  cluster_endpoint_public_access  = true

  # This will install the required addons directly once the cluster is launched
  cluster_addons = {
    coredns = {
      most_recent = true
    }
    kube-proxy = {
      most_recent = true
    }
    vpc-cni = {
      most_recent = true
    }
  }

  vpc_id                   = "vpc-xxxxxxxxxxx"
  subnet_ids               = ["subnet-01xxxxxx", "subnet-02xxxxxx", "subnet-03xxxxxx"]
  control_plane_subnet_ids = ["subnet-04xxxxxx", "subnet-05xxxxxx", "subnet-06xxxxxx"]

  # Self Managed Node Group(s)
  self_managed_node_group_defaults = {
    instance_type                          = "m6i.large"
    update_launch_template_default_version = true
    iam_role_additional_policies = {
      AmazonSSMManagedInstanceCore = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
    }
  }

  self_managed_node_groups = {
    one = {
      name         = "mixed-1"
      max_size     = 5
      desired_size = 2

      use_mixed_instances_policy = true
      mixed_instances_policy = {
        instances_distribution = {
          on_demand_base_capacity                  = 0
          on_demand_percentage_above_base_capacity = 10
          spot_allocation_strategy                 = "capacity-optimized"
        }

        override = [
          {
            instance_type     = "m5.xlarge"
            weighted_capacity = "1"
          },
          {
            instance_type     = "m6i.large"
            weighted_capacity = "2"
          },
        ]
      }
    }
  }

  # EKS Managed Node Group(s)
  eks_managed_node_group_defaults = {
    instance_types = ["m6i.large", "m5.large", "m5n.large", "m5zn.large"]
  }

  eks_managed_node_groups = {
    blue = {}
    green = {
      min_size     = 1
      max_size     = 10
      desired_size = 1

      instance_types = ["t3.large"]
      capacity_type  = "SPOT"
    }
  }


  # aws-auth configmap
  manage_aws_auth_configmap = true

  # IAM role to the EC2 Nodes
  aws_auth_roles = [
    {
      rolearn  = "arn:aws:iam::66666666666:role/role1"
      username = "role1"
      groups   = ["system:masters"]
    },
  ]
  # Grant IAM users permissions to EKS cluster
  aws_auth_users = [
    {
      userarn  = "arn:aws:iam::66666666666:user/user1"
      username = "user1"
      groups   = ["system:masters"]
    },
    {
      userarn  = "arn:aws:iam::66666666666:user/user2"
      username = "user2"
      groups   = ["system:masters"]
    },
  ]

  tags = {
    Environment = "dev"
    Terraform   = "true"
    Organisation = "TasrieIT"
  }
}

Launching the EKS Cluster

Initialize and run the Terraform configuration to provision the EKS cluster resources.

First run the terraform init command to initialize. This command will download all the required files to run the terraform EKS module.

sh
terraform init

once the above command is completed. Now run the terraform plan command.

sh
terraform plan

Now, once the plan is ready you can successfully run the terraform apply command.

sh
terraform apply

Monitoring the Provisioning Process

Monitor the provisioning process by checking the Terraform output console and AWS console for errors.

Configuring the EKS Cluster

Once the EKS cluster is provisioned, we need to perform several configurations to access it:

Accessing the EKS Cluster

Access the EKS cluster using the Kubernetes command line tool (kubectl) and AWS command line interface (CLI). Configure access credentials and endpoint using the command line interface.

sh
aws eks update-kubeconfig --region eu-west-1 --name <cluster-name> --profile <profile-name>

This command will generate or append the kubeconfig configuration to ~/.kube/config.

If you have default profile configured you can remove the --profile

sh
aws eks update-kubeconfig --region eu-west-1 --name <cluster-name>

If you want to save it to a different config file you can run this command

sh
aws eks update-kubeconfig --region eu-west-1 --name <cluster-name> --profile <profile-name> --kubeconfig /path/to/save/tasrie-eks-cluster.config

Deploying Applications to the EKS Cluster

Deploy containerized applications to the EKS cluster using following Kubernetes manifests.

Save the content to a file called deployment.yaml

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: nginx
spec:
  selector:
    app: nginx
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80

Run the following command to install the kubernetes deployment

sh
kubectl apply -f deployment.yaml

Once the command is run, this kubernetes manifest will create a deployment and a service.

To test if the nginx is successfully deployed.

Run the following command. This command will do port-forwarding from your local machine to the kubernetes cluster.

sh
kubectl port-forward svc/nginx 8080:80

Once the command is successfully ran. you can now launch your favourite browser and launch http://localhost:8080

you should see a nginx page. which mean the app is successfully deployed and your EKS cluster is completely ready.

Scaling the EKS Cluster

Scale the EKS cluster by modifying the node group configuration or adding additional nodes to the cluster.

Testing and Troubleshooting the EKS Cluster

To ensure the EKS cluster is functioning properly, we need to perform several tests and resolve any issues:

Testing the EKS Cluster

Test the EKS cluster by deploying test applications and monitoring their health.

Identifying and Resolving Issues

Identify and resolve any issues with the EKS cluster by checking error logs and troubleshooting.

Best Practices for Managing EKS with Terraform

To effectively manage an EKS cluster with Terraform, consider the following best practices:

Keeping Terraform State Secure

Keep Terraform state files secure by storing them in a safe location and restricting access to them.

Avoiding Manual Configuration Changes

Avoid manually modifying EKS resources as Terraform may not reflect the changes made outside of its configuration. Any necessary changes should be made within Terraform to ensure consistency and prevent configuration drift.

Conclusion

In conclusion, the Terraform EKS Module is a powerful tool for provisioning and managing EKS clusters on AWS. By leveraging this module, users can provision an EKS cluster in less than 30 minutes and manage it using Terraform’s declarative language and infrastructure-as-code principles. With proper configuration and best practices, EKS can provide a scalable, secure, and highly available platform for deploying containerized applications on AWS.

For more such content, make sure to check out our latest tech blog

Follow our LinkedIn Page

illustration
Need Expert Help ?

At Tasrie IT, we assist businesses in their growth and addressing intricate issues by utilizing advanced cloud technologies and contemporary platform engineering techniques.

Related Posts