profile for Gajendra D Ambi on Stack Exchange, a network of free, community-driven Q&A sites

Friday, February 10, 2023

Static IP address for a VM on k8s via kube-virt

KubeVirt is an open-source project that allows you to run virtual machines (VMs) on top of Kubernetes. If you want to assign a static IP to a VM running in KubeVirt, you will need to configure the network settings for the VM.

You might be familiar with metallb loadbalancer on k8s. You create an ip pool or multiple ip pools and when a service requests an IP, It will auto assign the IP.

Similarly you create an ip pool here an ip pool, when you create VMs, They will automatically get one IP with kube virt.

Here are the steps to assign a static IP to a VM in KubeVirt:

  1. Create a Network Attachment Definition (NAD) that specifies the static IP address you want to assign to the VM. For example: 
apiVersion: k8s.cni.cncf.io/v1
kind: NetworkAttachmentDefinition
metadata:
  name: my-static-ip-network
spec:
  config: '{
      "cniVersion": "0.3.0",
      "name": "my-static-ip-network",
      "type": "ipvlan",
      "ipam": {
          "type": "host-local",
          "subnet": "10.244.0.0/16",
          "routes": [
              { "dst": "0.0.0.0/0" }
          ],
          "ranges": [
              [
                  {
                      "subnet": "10.244.0.0/24",
                      "gateway": "10.244.0.1"
                  }
              ]
          ],
          "config": [
              {
                  "subnet": "10.244.0.0/24",
                  "gateway": "10.244.0.1",
                  "ipMasq": true
              }
          ]
      }
  }'

    
       2. Apply the NAD to your Kubernetes cluster using kubectl apply:
kubectl apply -f my-static-ip-network.yaml 
      3. Update your VM definition to use the NAD. This can be done by adding a network section to the spec section of your VM definition. For example:
apiVersion: kubevirt.io/v1alpha3
kind: VirtualMachine
metadata:
  name: my-vm
spec:
  running: false
  template:
    metadata:
      labels:
        kubevirt.io/vm: my-vm
    spec:
      domains:
        - type: kvm
          resources:
            requests:
              memory: 64M
          devices:
            interfaces:
            - name: eth0
              bridge: {}
              network: my-static-ip-network
              model: virtio
              macAddress: "52:54:00:12:34:56"
   4. Apply the updated VM definition to your Kubernetes cluster using kubectl apply: 
kubectl apply -f my-vm.yaml
Once the VM is started, it should be assigned the static IP address specified in the NAD. You can verify this by checking the IP address of the VM from within the VM or by using kubectl get pod to inspect the network configuration of the pod that represents the VM in Kubernetes.

No comments:

Post a Comment