下载安装
curl -L -o kubebuilder https://go.kubebuilder.io/dl/latest/$(go env GOOS)/$(go env GOARCH)
chmod +x kubebuilder && mv kubebuilder /usr/local/bin/
创建一个项目
mkdir vm-operator
cd vm-operator
go mod init vm-operator
kubebuilder init --domain cloud.com --owner "yuanqh" --skip-go-version-check
kubebuilder create api --group hft --version v1 --kind VirtualMachine
执行kubebuilder create api发生下面错误
make: *** [generate] Error 1
Error: failed to create API: unable to run post-scaffold tasks of "base.go.kubebuilder.io/v3": exit status 2
则需要安装gcc
yum install gcc
如果没有tree命令
yum -y install tree
执行tree 可以看到当前目录的结构
[root@k8s-master01 vm-operator]# tree .
.
├── api
│ └── v1
│ ├── groupversion_info.go
│ ├── virtualmachined_types.go
│ └── zz_generated.deepcopy.go
├── bin
│ └── controller-gen
├── config
│ ├── crd
│ │ ├── bases
│ │ │ └── hft.cloud.com_virtualmachineds.yaml
│ │ ├── kustomization.yaml
│ │ ├── kustomizeconfig.yaml
│ │ └── patches
│ │ ├── cainjection_in_virtualmachineds.yaml
│ │ └── webhook_in_virtualmachineds.yaml
VirtualMachinedSpec对象添加如下属性
UUID string `json:"uuid,omitempty"`
Name string `json:"name,omitempty"`
Image string `json:"image,omitempty"`
Memory int `json:"memory,omitempty"`
Disk int `json:"disk,omitempty"`
需要注意 json:"disk,omitempty"
的格式
修改属性后重新生成代码
make manifests generate
安装到k8s集群中
make install
make指令含义,可以通过make help查看帮助,具体如下:
[root@k8s-master01 vm-operator]# make help
Usage:
make <target>
General
help Display this help.
Development
manifests Generate WebhookConfiguration, ClusterRole and CustomResourceDefinition objects.
generate Generate code containing DeepCopy, DeepCopyInto, and DeepCopyObject method implementations.
fmt Run go fmt against code.
vet Run go vet against code.
test Run tests.
Build
build Build manager binary.
run Run a controller from your host.
docker-build Build docker image with the manager.
docker-push Push docker image with the manager.
Deployment
install Install CRDs into the K8s cluster specified in ~/.kube/config.
uninstall Uninstall CRDs from the K8s cluster specified in ~/.kube/config. Call with ignore-not-found=true to ignore resource not found errors during deletion.
deploy Deploy controller to the K8s cluster specified in ~/.kube/config.
undeploy Undeploy controller from the K8s cluster specified in ~/.kube/config. Call with ignore-not-found=true to ignore resource not found errors during deletion.
controller-gen Download controller-gen locally if necessary.
kustomize Download kustomize locally if necessary.
envtest Download envtest-setup locally if necessary.