How do I restrict CIDR IP addresses for a LoadBalancer type service in Amazon EKS?

Last updated: 2021-08-23

I want to restrict CIDR IP addresses for a LoadBalancer type service in Amazon Elastic Kubernetes Service (Amazon EKS).

Short description

If you create a service of type:LoadBalancer, then requests from the source 0.0.0.0/0 are allowed by default. If your load balancer is in a public subnet, then requests are routed to worker nodes from anywhere on the internet.

Resolution

Note: If you receive errors when running AWS Command Line Interface (AWS CLI) commands, make sure that you’re using the most recent AWS CLI version.

Set up your environment

1.    Create an Amazon EKS cluster.

2.    Create and launch worker nodes.

3.    Set up kubectl.

4.    Set up the AWS CLI.

5.    Set up the AWS Load Balancer Controller.

Note: The AWS Load Balancer Controller supports the following versions of the AWS Network Load Balancer for Services of type LoadBalancer: NLB ip mode (version 2.0.0 or above) and NLB instance mode (2.2.0 or above)

Important: It's a best practice to use the AWS Load Balancer Controller when you provision a new Network Load Balancer for Services of type LoadBalancer. Use the AWS Load Balancer Controller instead of the Kubernetes in-tree service load balancer controller.

Restrict CIDR IP addresses

1.    In your service manifest file (svc.yaml), add the .spec.loadBalancerSourceRanges field. For example:

apiVersion: v1
kind: Service
metadata:
  labels:
    app: nginx
  name: nginx
  annotations:
    service.beta.kubernetes.io/aws-load-balancer-type: "external"
    service.beta.kubernetes.io/aws-load-balancer-nlb-target-type: "instance"
    service.beta.kubernetes.io/aws-load-balancer-scheme: "internet-facing"
spec:
  ports:
  - port: 80
    protocol: TCP
    targetPort: 80
  selector:
    app: nginx
  type: LoadBalancer
  loadBalancerSourceRanges:
  - "143.231.0.0/16"

2.    To apply the manifest file, run the following command:

$ kubectl apply -f svc.yaml

3.    To confirm that the inbound rules on the security group are modified, run the following AWS CLI command:

$ aws ec2 describe-security-groups --group-ids sg-XXXXXXXXXXXXXXXXX
...
    "CidrIp": "143.231.0.0/16"
...

Finally, consider the following:

If you use NLB ip mode, then the .spec.loadBalancerSourceRanges field is ignored by default. In this case, use the following annotation:

service.beta.kubernetes.io/aws-load-balancer-target-group-attributes: preserve_client_ip.enabled=true

This annotation enables Client IP preservation.

For a service with a Network Load Balancer type, consider the maximum security group limit. For each node port and subnet CIDR range, the controller creates rules on the worker node's security group.


Did this article help?


Do you need billing or technical support?