KubeVirt is an extension of Kubernetes, enabling it to manage virtual machines.I have deployed a KubeVirt cluster. I want to use Python Client to operate KubeVirt to manage virtual machines. Is this feasible?
I use Kubernetes Python Client.But it does not seem to support the resource type of virtual machine.My cluster can create virtual machines through kubectl apply - f testvm.yaml
Python code:
from kubernetes import client, config, utils
config.load_kube_config('config')
k8s_client = client.ApiClient()
file = 'yamlfile\\testvm.yaml'
utils.create_from_yaml(k8s_client, file, verbose=True)
error:
AttributeError: module 'kubernetes.client' has no attribute 'KubevirtIoV1Api'
testvm.yaml:
apiVersion: kubevirt.io/v1
kind: VirtualMachine
metadata:
name: testvm
spec:
running: false
template:
metadata:
labels:
kubevirt.io/size: small
kubevirt.io/domain: testvm
spec:
domain:
devices:
disks:
- name: containerdisk
disk:
bus: virtio
- name: cloudinitdisk
disk:
bus: virtio
interfaces:
- name: default
masquerade: {}
resources:
requests:
memory: 64M
networks:
- name: default
pod: {}
volumes:
- name: containerdisk
containerDisk:
image: quay.io/kubevirt/cirros-container-disk-demo
- name: cloudinitdisk
cloudInitNoCloud:
userDataBase64: SGkuXG4=
---
apiVersion: v1
kind: Service
metadata:
name: vm-ssh
spec:
type: NodePort
ports:
- protocol: TCP
port: 24
targetPort: 22
name: test
selector:
kubevirt.io/domain: testvm
kubevirt.io/size: small
You're trying to create resources that use the kubevirt.io/v1
api. This isn't a core Kubernetes API; it's provided by the kubevirt custom resource definition, which means it's not supported by any of the static parts of the Python kubernetes client.
But don't worry, that's what the DynamicClient is for! You can find some examples of working with the dynamic client here.
Your code would end up looking something like:
import yaml
from kubernetes import config, dynamic
from kubernetes.client import api_client
# Creating a dynamic client
client = dynamic.DynamicClient(
api_client.ApiClient(configuration=config.load_kube_config())
)
# fetching the configmap api
api = client.resources.get(api_version="kubevirt.io/v1", kind="VirtualMachine")
path = 'testvm.yaml'
with open(path) as fd:
resource = yaml.safe_load(fd)
api.create(body=resource)