0

I set an EKS cluster using Terraform. I try to set Route53 record to map my domain name, to the load balancer of my cluster.

I set my EKS cluster:

resource "aws_eks_cluster" "main" {
  name     = "${var.project}-cluster"
  role_arn = aws_iam_role.cluster.arn
  version  = "1.24"

  vpc_config {
    subnet_ids              = flatten([aws_subnet.public[*].id, aws_subnet.private[*].id])
    endpoint_private_access = true
    endpoint_public_access  = true
    public_access_cidrs     = ["0.0.0.0/0"]
  }

  tags = merge(
    var.tags,
    {
      Stack = "backend"
      Name  = "${var.project}-eks-cluster",
    }
  )

  depends_on = [
    aws_iam_role_policy_attachment.cluster_AmazonEKSClusterPolicy
  ]
}

And I have created the following k8s service:

apiVersion: v1
kind: Service
metadata:
    name: backend-service
spec:
    selector:
        app: dashboard-backend
    type: LoadBalancer
    ports:
        - protocol: TCP
          port: '$PORT'
          targetPort: '$PORT'

As far as I know, once I deploy a k8s service, AWS automatically generates an ALB resource for my service. So, I set this route53 sources:

resource "aws_route53_zone" "primary" {
  name = var.domain_name

  tags = merge(
    var.tags,
    {
      Name = "${var.project}-Route53-zone",
    }
  )
}

data "kubernetes_service" "backend" {
  metadata {
    name = "backend-service"
  }
}


resource "aws_route53_record" "backend_record" {
  zone_id = aws_route53_zone.primary.zone_id
  name    = "www.api"
  type    = "A"
  ttl     = "300"

  alias {
    name                   = data.kubernetes_service.backend.status.0.load_balancer.0.ingress.0.hostname
    zone_id                = ??????
    evaluate_target_health = true
  }
}

I did get the load balancer host name using data.kubernetes_service.backend.status.0.load_balancer.0.ingress.0.hostname, but how can I get its zone ID to use in zone_id key?

1 Answer 1

1

There is no direct way to get the zone_id of the load balancer from the kubernetes_service data source. It can only provide you the ip and hostname. Refer: https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs/data-sources/service#ingress

You can get the aws elb hosted zone id using the data source aws_elb_hosted_zone_id.

data "aws_elb_hosted_zone_id" "elb_zone_id" {}

resource "aws_route53_record" "backend_record" {
  zone_id = aws_route53_zone.primary.zone_id
  name    = "www.api"
  type    = "A"
  ttl     = "300"

  alias {
    name                   = data.kubernetes_service.backend.status.0.load_balancer.0.ingress.0.hostname
    zone_id                = data.aws_elb_hosted_zone_id.elb_zone_id.id
    evaluate_target_health = true
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.