快速开始

这个 Quick Start 指南包括:

环境准备

  • go version v1.13+.
  • docker version 17.03+.
  • kubectl version v1.11.3+.
  • kustomize v3.1.0+
  • Access to a Kubernetes v1.11.3+ cluster.

安装

安装 kubebuilder:

os=$(go env GOOS) arch=$(go env GOARCH) # download kubebuilder and extract it to tmp curl -L https://go.kubebuilder.io/dl/2.2.0/${os}/${arch} | tar -xz -C /tmp/ # move to a long-term location and put it on your path # (you'll need to set the KUBEBUILDER_ASSETS env var if you put it somewhere else) sudo mv /tmp/kubebuilder_2.2.0_${os}_${arch} /usr/local/kubebuilder export PATH=$PATH:/usr/local/kubebuilder/bin

创建一个 Project

创建一个目录,然后运行 init 命令以初始化新项目

mkdir $GOPATH/src/example cd $GOPATH/src/example kubebuilder init --domain my.domain

创建一个 API

运行以下命令创建一个新的 API(group/version) -->webapp/v1, 并在此 API 上创建一个新的 Kind(CRD) --> Guestbook

kubebuilder create api --group webapp --version v1 --kind Guestbook

备注: 对于如何设计 API 和如何实现业务逻辑可以参考 Designing an APIWhat’s in a Controller.

查看示例 `(api/v1/guestbook_types.go)`

// GuestbookSpec defines the desired state of Guestbook type GuestbookSpec struct { // INSERT ADDITIONAL SPEC FIELDS - desired state of cluster // Important: Run "make" to regenerate code after modifying this file // Quantity of instances // +kubebuilder:validation:Minimum=1 // +kubebuilder:validation:Maximum=10 Size int32 `json:"size"` // Name of the ConfigMap for GuestbookSpec's configuration // +kubebuilder:validation:MaxLength=15 // +kubebuilder:validation:MinLength=1 ConfigMapName string `json:"configMapName"` // +kubebuilder:validation:Enum=Phone;Address;Name Type string `json:"alias,omitempty"` } // GuestbookStatus defines the observed state of Guestbook type GuestbookStatus struct { // INSERT ADDITIONAL STATUS FIELD - define observed state of cluster // Important: Run "make" to regenerate code after modifying this file // PodName of the active Guestbook node. Active string `json:"active"` // PodNames of the standby Guestbook nodes. Standby []string `json:"standby"` } type Guestbook struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec GuestbookSpec `json:"spec,omitempty"` Status GuestbookStatus `json:"status,omitempty"` }

在本地运行 operator

你需要一个 Kubernetes 测试集群来进行测试,你可以使用 KIND 来启动一个本地或者远程的测试集群

在集群中安装 CRDs

make install

运行 controller (这个命令不会再后台运行 controller,所以建议新建一个 terminal 运行以下命令)

make run

安装 Custom Resources 实例

创建 Project时,对于 Create Resource [y/n],如果你选择 y, 将会在 config/samples/ 目录中为你的 CRD 创建一个 CR 文件 xxx.yaml (如果你修改了 API 定义文件(api/v1/guestbook_types.go),请务必修改此文件)

kubectl apply -f config/samples/

在集群上运行 operator

Build 并 Push 镜像 IMG:

make docker-build docker-push IMG=<some-registry>/<project-name>:tag

使用指定镜像IMG将 operator 部署到集群中:

make deploy IMG=<some-registry>/<project-name>:tag

卸载 CRDs

从集群中删除 CRDs:

make uninstall

下一步

现在,请继续学习 CronJob tutorial 教程,通过开发演示示例项目更好地了解其工作原理。