TExcelTAD

EKS in Code

The roadmap's capstone provisions "a cloud VPC, a managed database and an EKS cluster" with IaC. Containers: ECS, EKS, Fargate, ECR introduced EKS; Managed Kubernetes compared it with GKE and AKS. Here is a minimal, production-shaped EKS cluster written directly with AWS resources, so you can see every moving part before reaching for a community module.

An EKS cluster in code consists of:

Piece Resources
the control plane's IAM role aws_iam_role trusted by eks.amazonaws.com, with AmazonEKSClusterPolicy
the control plane aws_eks_cluster: version, subnets, endpoint access, authentication mode
who may use the cluster aws_eks_access_entry + aws_eks_access_policy_association (the API replacing the old aws-auth ConfigMap)
the nodes' IAM role aws_iam_role trusted by ec2.amazonaws.com, with the worker node, CNI and ECR read-only policies
the nodes aws_eks_node_group: instance types, scaling, subnets
add-ons aws_eks_addon for vpc-cni, coredns, kube-proxy, eks-pod-identity-agent

The code, planned offline

bash · try it yourself
mkdir eks && cd eks
cat > offline.tf <<'HCL'
provider "aws" {
  region                      = "eu-west-1"
  access_key                  = "offline"
  secret_key                  = "offline"
  skip_credentials_validation = true
  skip_requesting_account_id  = true
  skip_metadata_api_check     = true
}
HCL
cat > main.tf <<'HCL'
terraform {
  required_providers {
    aws = { source = "hashicorp/aws", version = "~> 6.0" }
  }
}

variable "name" {
  type    = string
  default = "linkly-prod"
}
variable "kubernetes_version" {
  type    = string
  default = "1.36"                  # check which versions EKS currently supports
}
variable "private_subnet_ids" {
  type    = list(string)
  default = ["subnet-0aaa1111bbbb22223", "subnet-0ccc3333dddd44445", "subnet-0eee5555ffff66667"]
}
variable "admin_role_arn" {
  type    = string
  default = "arn:aws:iam::123456789012:role/platform-admin"
}

data "aws_iam_policy_document" "eks_assume" {
  statement {
    actions = ["sts:AssumeRole", "sts:TagSession"]
    principals {
      type        = "Service"
      identifiers = ["eks.amazonaws.com"]
    }
  }
}

data "aws_iam_policy_document" "nodes_assume" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type        = "Service"
      identifiers = ["ec2.amazonaws.com"]
    }
  }
}

resource "aws_iam_role" "cluster" {
  name               = "${var.name}-eks-cluster"
  assume_role_policy = data.aws_iam_policy_document.eks_assume.json
}

resource "aws_iam_role_policy_attachment" "cluster" {
  role       = aws_iam_role.cluster.name
  policy_arn = "arn:aws:iam::aws:policy/AmazonEKSClusterPolicy"
}

resource "aws_eks_cluster" "this" {
  name     = var.name
  version  = var.kubernetes_version
  role_arn = aws_iam_role.cluster.arn

  vpc_config {
    subnet_ids              = var.private_subnet_ids
    endpoint_private_access = true
    endpoint_public_access  = false          # API reachable from inside the VPC (VPN, CI runners) only
  }

  access_config {
    authentication_mode                         = "API"
    bootstrap_cluster_creator_admin_permissions = false
  }

  depends_on = [aws_iam_role_policy_attachment.cluster]
}

resource "aws_eks_access_entry" "admin" {
  cluster_name  = aws_eks_cluster.this.name
  principal_arn = var.admin_role_arn
}

resource "aws_eks_access_policy_association" "admin" {
  cluster_name  = aws_eks_cluster.this.name
  principal_arn = var.admin_role_arn
  policy_arn    = "arn:aws:eks::aws:cluster-access-policy/AmazonEKSClusterAdminPolicy"
  access_scope {
    type = "cluster"
  }
}

resource "aws_iam_role" "nodes" {
  name               = "${var.name}-eks-nodes"
  assume_role_policy = data.aws_iam_policy_document.nodes_assume.json
}

resource "aws_iam_role_policy_attachment" "nodes" {
  for_each = toset([
    "AmazonEKSWorkerNodePolicy",
    "AmazonEKS_CNI_Policy",
    "AmazonEC2ContainerRegistryReadOnly",
  ])
  role       = aws_iam_role.nodes.name
  policy_arn = "arn:aws:iam::aws:policy/${each.key}"
}

resource "aws_eks_node_group" "default" {
  cluster_name    = aws_eks_cluster.this.name
  node_group_name = "default"
  node_role_arn   = aws_iam_role.nodes.arn
  subnet_ids      = var.private_subnet_ids
  instance_types  = ["m7g.large"]
  ami_type        = "AL2023_ARM_64_STANDARD"

  scaling_config {
    min_size     = 2
    desired_size = 3
    max_size     = 6
  }

  update_config {
    max_unavailable = 1
  }

  lifecycle {
    ignore_changes = [scaling_config[0].desired_size]   # the cluster autoscaler / Karpenter owns it
  }

  depends_on = [aws_iam_role_policy_attachment.nodes]
}

resource "aws_eks_addon" "this" {
  for_each     = toset(["vpc-cni", "coredns", "kube-proxy", "eks-pod-identity-agent"])
  cluster_name = aws_eks_cluster.this.name
  addon_name   = each.key
}

output "cluster_name" {
  value = aws_eks_cluster.this.name
}
HCL
tofu init >/dev/null
tofu validate
tofu plan -out=tfplan | grep '^Plan:'
tofu show -json tfplan | jq -r '.resource_changes[] | .type' | sort | uniq -c
Success! The configuration is valid.
Plan: 14 to add, 0 to change, 0 to destroy.
      1 aws_eks_access_entry
      1 aws_eks_access_policy_association
      4 aws_eks_addon
      1 aws_eks_cluster
      1 aws_eks_node_group
      2 aws_iam_role
      4 aws_iam_role_policy_attachment

Fourteen resources for a cluster with one node group, and nothing for the workloads yet. Things worth noticing:

  • depends_on on the policy attachments. The cluster and nodes reference the roles, not the attachments, but EKS fails (or, worse, can't clean up on destroy) if the policies aren't attached first.
  • Access entries (authentication_mode = "API") declare who may administer the cluster in code; with bootstrap_cluster_creator_admin_permissions = false, not even the pipeline role that created the cluster gets hidden admin rights.
  • ignore_changes on desired_size: an autoscaler changes it at run time, and every plan would otherwise reset it (Resources & Meta-Arguments).
  • A private API endpoint means kubectl and the Kubernetes/Helm providers must run from inside the VPC (a VPN, or CI runners in the VPC). Teams that can't do that enable the public endpoint with public_access_cidrs limited to known addresses.

Installing things into the cluster

The kubernetes and helm providers can deploy into the cluster from the same or (better) a separate configuration, authenticating with a short-lived token from the AWS CLI:

hcl
data "aws_eks_cluster" "this" {
  name = "linkly-prod"
}

provider "helm" {
  kubernetes = {                       # helm provider 3.x: an attribute, not a block
    host                   = data.aws_eks_cluster.this.endpoint
    cluster_ca_certificate = base64decode(data.aws_eks_cluster.this.certificate_authority[0].data)
    exec = {
      api_version = "client.authentication.k8s.io/v1beta1"
      command     = "aws"
      args        = ["eks", "get-token", "--cluster-name", data.aws_eks_cluster.this.name]
    }
  }
}

resource "helm_release" "metrics_server" {
  name       = "metrics-server"
  namespace  = "kube-system"
  repository = "https://kubernetes-sigs.github.io/metrics-server/"
  chart      = "metrics-server"
  version    = "3.14.0"
}

Keep the cluster and what runs on it in separate states: a provider configured from a resource that doesn't exist yet (during the first apply, or when the cluster is replaced) is a well-known source of failed plans. Application workloads usually don't belong in Terraform at all: Helm charts deployed by a GitOps tool such as Argo CD are the roadmap's way (GitOps, Helm & Kustomize). Platform add-ons (ingress or Gateway API controllers, cert-manager, external-dns, Argo CD itself) are a common grey zone that many teams do install with the Helm provider.

Or use the community module

terraform-aws-modules/eks/aws wraps all of the above (and much more: Karpenter, Fargate profiles, IRSA and Pod Identity, KMS encryption of secrets):

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

  name               = "linkly-prod"
  kubernetes_version = "1.36"
  vpc_id             = module.vpc.vpc_id
  subnet_ids         = module.vpc.private_subnets

  eks_managed_node_groups = {
    default = {
      instance_types = ["m7g.large"]
      ami_type       = "AL2023_ARM_64_STANDARD"
      min_size       = 2
      max_size       = 6
      desired_size   = 3
    }
  }
}

It is a large module; read the upgrade guide before every major version. Knowing the underlying resources, as in this lesson, is what lets you debug it.

Cost: an EKS control plane has an hourly fee, nodes are EC2 instances, and NAT gateways and load balancers add more. Check current pricing, and destroy practice clusters the same day (tofu destroy), or follow the free local track of the DevOps Capstone.

Test yourself

Why does aws_eks_node_group need depends_on on the node role's policy attachments?

  1. Node groups can't reference IAM roles
  2. The node group references the role, not the attachments, yet nodes can't join the cluster until the policies are attached
  3. To make the plan shorter
  4. It is required by the registry

What do EKS access entries replace?

  1. Node groups
  2. The aws-auth ConfigMap for mapping IAM principals to cluster permissions
  3. Security groups
  4. Add-ons

Why put desired_size in ignore_changes?

  1. It can't be set
  2. An autoscaler changes it at run time, and plans would otherwise keep resetting it
  3. To save money
  4. AWS ignores it anyway