Skip to main content

Command Palette

Search for a command to run...

Network Policy Assignment

Updated
2 min readView as Markdown

Following is an assignment of creating a network policy from the following instructions.

Instructions :

The assignment requires you to create a YAML file for a network policy in Kubernetes that meets the following requirements:

  • Name of the network policy will be db-network-policy.

  • This network policy will apply on db pod, and the label of db-pod is role: db-pod.

  • Ingress traffic will come from another pod that is internal pod, and the label of the internal-pod is role: internal-db. This internal pod is present in the dev namespace, and ingress traffic will come on port number 8080.

  • Egress traffic will go to server present outside the cluster whose IP address range is 172.17.0.0/16, except for 172.17.1.0/24. Egress traffic should come in port range 30000 to 32768.

Network policy file would look like this -

network-policy.yaml

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: db-network-policy
  namespace: default
spec:
  podSelector:
    matchLabels:
      role: db-pod
  policyTypes:
  - Ingress
  - Egress
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          kubernetes.io/metadata.name: dev
       podSelector:
        matchLabels:
          role: internal-db
    ports:
    - protocol: TCP
      port: 8080
  egress:
  - to:
    - ipBlock:
        cidr: 172.17.0.0/16
        except:
        - 172.17.1.0/24

    ports:
    - protocol: TCP
      port: 30000
      endPort: 32768

To find the namespace label used this command
#kubectl get ns dev --show-labels

When writing a NetworkPolicy, you can target a range of ports instead of a single port.This is achievable with the usage of the endPort field

IP addresses in the ranges 172.17.0.0172.17.0.255 and 172.17.2.0172.17.255.255 (ie, all of 172.17.0.0/16 except 172.17.1.0/24), this is achieved through "except".

PS: Credit to this github repository for the assignment task
https://github.com/devopsproin/certified-kubernetes-administrator/tree/main/Network-Policy/Assignment