Skip to content
This repository was archived by the owner on Nov 4, 2024. It is now read-only.

Commit 14f2e12

Browse files
committed
refactor: use client go to invoke k8s api
Use golang client to invoke Kubernetes API directly from the code, in order to test the functionality as well. Signed-off-by: Ben Oukhanov <[email protected]>
1 parent d19a04c commit 14f2e12

File tree

1 file changed

+28
-19
lines changed

1 file changed

+28
-19
lines changed

main.go

Lines changed: 28 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import (
77
"os"
88
"os/exec"
99
"strconv"
10-
"strings"
1110
"time"
1211

1312
"github.com/google/go-containerregistry/pkg/authn"
@@ -18,6 +17,11 @@ import (
1817
"github.com/google/go-containerregistry/pkg/v1/tarball"
1918

2019
cobra "github.com/spf13/cobra"
20+
corev1 "k8s.io/api/core/v1"
21+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
22+
kvcorev1 "kubevirt.io/api/core/v1"
23+
v1beta1 "kubevirt.io/api/export/v1beta1"
24+
kubecli "kubevirt.io/client-go/kubecli"
2125
tar "kubevirt.io/containerdisks/pkg/build"
2226
)
2327

@@ -30,26 +34,31 @@ const (
3034
func applyVirtualMachineExport(vmName string) error {
3135
log.Println("Applying VirtualMachineExport object...")
3236

33-
yaml := fmt.Sprintf(`
34-
apiVersion: export.kubevirt.io/v1alpha1
35-
kind: VirtualMachineExport
36-
metadata:
37-
name: %s
38-
spec:
39-
source:
40-
apiGroup: "kubevirt.io"
41-
kind: VirtualMachine
42-
name: %s
43-
`, vmName, vmName)
44-
cmd := exec.Command("kubectl", "apply", "-f", "-")
45-
cmd.Stdin = strings.NewReader(yaml)
46-
cmd.Stdout = os.Stdout
47-
cmd.Stderr = os.Stderr
48-
49-
if err := cmd.Run(); err != nil {
37+
client, err := kubecli.GetKubevirtClient()
38+
if err != nil {
5039
return err
5140
}
52-
return nil
41+
42+
vmNamespace := os.Getenv("VM_NAMESPACE")
43+
if vmNamespace == "" {
44+
return fmt.Errorf("VM namespace is not defined. Set VM_NAMESPACE.")
45+
}
46+
47+
vmExport := &v1beta1.VirtualMachineExport{
48+
ObjectMeta: metav1.ObjectMeta{
49+
Name: vmName,
50+
},
51+
Spec: v1beta1.VirtualMachineExportSpec{
52+
Source: corev1.TypedLocalObjectReference{
53+
APIGroup: &kvcorev1.GroupVersion.Version,
54+
Kind: kvcorev1.VirtualMachineGroupVersionKind.Kind,
55+
Name: vmName,
56+
},
57+
},
58+
}
59+
60+
_, err = client.VirtualMachineExport(vmNamespace).Create(context.Background(), vmExport, metav1.CreateOptions{})
61+
return err
5362
}
5463

5564
func downloadVirtualMachineDiskImage(vmName, volumeName string) error {

0 commit comments

Comments
 (0)