touati ahmed
touati ahmed

Reputation: 411

How to create an EKS cluster with public and private subnets using terraform?

I'm usin terraform to set up an EKS cluster i need to make sure that my worker nodes will be placed on private subnets and that my public subnets will be used for my load balancers but i don't actually know how to inject public and private subnets in my cluster because i'm only using private ones.

resource "aws_eks_cluster" "master_node" {
    name     = "my-cluster"
    role_arn = aws_iam_role.master_iam_role.arn
    version  = "1.14"
    vpc_config {
        security_group_ids      = [aws_security_group.master_security_group.id]
        subnet_ids              = var.private_subnet_eks_ids
    }

    depends_on = [
        aws_iam_role_policy_attachment.main-cluster-AmazonEKSClusterPolicy,
        aws_iam_role_policy_attachment.main-cluster-AmazonEKSServicePolicy,
    ]
}

resource "aws_autoscaling_group" "eks_autoscaling_group" {
    desired_capacity     = var.desired_capacity
    launch_configuration = aws_launch_configuration.eks_launch_config.id
    max_size             = var.max_size
    min_size             = var.min_size
    name                 = "my-autoscaling-group"
    vpc_zone_identifier  = var.private_subnet_eks_ids
    depends_on = [
        aws_efs_mount_target.efs_mount_target
    ]
}

Upvotes: 3

Views: 3160

Answers (2)

Fabio Formosa
Fabio Formosa

Reputation: 1084

Give only private subnets to your eks cluster but, before that, make sure you've tagged the public subnets so:

Key: kubernetes.io/role/elb
value: 1

as described here: https://aws.amazon.com/premiumsupport/knowledge-center/eks-vpc-subnet-discovery/

EKS will discover the public subnets where to place the load balancer querying by tags.

Upvotes: 2

Jonas
Jonas

Reputation: 128907

I make use to create both public and private subnets on the VPC using the vpc module. Then I create the EKS cluster using the eks module and refere to the vpc-data.

Example

module "vpc" {
  source = "terraform-aws-modules/vpc/aws"

  name = "my-vpc"
  cidr = "10.0.0.0/16"

  azs             = ["eu-north-1a", "eu-north-1b", "eu-north-1c"]
  private_subnets = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
  public_subnets  = ["10.0.101.0/24", "10.0.102.0/24", "10.0.103.0/24"]

  enable_nat_gateway = true
  enable_vpn_gateway = true
}

And then EKS cluster where I refer to the VPC subnets using module.vpc.private_subnets and module.vpc.vpc_id:

module "eks-cluster" {
  source               = "terraform-aws-modules/eks/aws"
  cluster_name         = "my-eks-cluster"
  cluster_version      = "1.17"
  subnets              = module.vpc.private_subnets
  vpc_id               = module.vpc.vpc_id

  worker_groups = [
    {
      instance_type = "t3.small"
      asg_max_size  = 2
    } 
  ]
}

Upvotes: 2

Related Questions