operator framework 是一个为云原生开发者提供开发operator的组件框架的开源项目,它目前包含三个组件:
Operator SDK。集成controller-runtime,提供了:编写运维逻辑的高阶API,快速构建Operator项目及代码生成的脚手架工具,覆盖常见Operator用例的扩展。Operator SDK是Operator Framework中最核心的工程。
Operator Lifecycle Manager:K8S集群内所有Operator(及其关联服务)的生命周期管理( installation, updates, and management )
Operator Metering (joining in the coming months):提供对operator本身的监控以提供一些定制化服务。
搭建开发环境主要用到operator SDK,下面主要介绍其安装和使用。
Mac OS
brew install operator-sdk
其他方式
参见官方安装指南
以官方的app-operator为例:
# 创建项目目录
mkdir -p $GOPATH/test/operator/
cd $GOPATH/test/operator/
# GO111MODULE=on 模块支持,go 会忽略 GOPATH 和 vendor 文件夹,只根据 go.mod 下载依赖。
export GO111MODULE=on
# 创建operator项目
operator-sdk new app-operator --repo github.com/example-inc/app-operator
cd app-operator
# 拓展kubernetes api
operator-sdk add api --api-version=app.example.com/v1alpha1 --kind=AppService
# 构建对应的controller基础代码
operator-sdk add controller --api-version=app.example.com/v1alpha1 --kind=AppService
# 可在对应的API文件中定义自己的需要的属性以及在对应的controller文件中构建自己的代码逻辑,完成之后按后续步骤构建镜像
# 构建镜像并推送到自己的镜像仓库
operator-sdk build kingdragon/app-operator:v1
docker push kingdragon/app-operator:v1
# 下为官方更改yaml文件里的镜像的shell命令
# 不熟悉shell命令,熟悉kubernetes yaml语法可自行到对应文件更改相关配置亦可
# Update the operator manifest to use the built image name (if you are performing these steps on OSX, see note below)
$ sed -i 's|REPLACE_IMAGE|kingdragon/app-operator:v1|g' deploy/operator.yaml
# On OSX use:
$ sed -i "" 's|REPLACE_IMAGE|kingdragon/app-operator:v1|g' deploy/operator.yaml
# 下为部署,根据自己的kubernetes集群环境自行部署。
# Setup Service Account
$ kubectl create -f deploy/service_account.yaml
# Setup RBAC
$ kubectl create -f deploy/role.yaml
$ kubectl create -f deploy/role_binding.yaml
# Setup the CRD
$ kubectl create -f deploy/crds/app.example.com_appservices_crd.yaml
# Deploy the app-operator
$ kubectl create -f deploy/operator.yaml
# Create an AppService CR
# The default controller will watch for AppService objects and create a pod for each CR
$ kubectl create -f deploy/crds/app.example.com_v1alpha1_appservice_cr.yaml
# Verify that a pod is created
$ kubectl get pod -l app=example-appservice
NAME READY STATUS RESTARTS AGE
example-appservice-pod 1/1 Running 0 1m
# Test the new Resource Type
$ kubectl describe appservice example-appservice
Name: example-appservice
Namespace: myproject
Labels: <none>
Annotations: <none>
API Version: app.example.com/v1alpha1
Kind: AppService
Metadata:
Cluster Name:
Creation Timestamp: 2018-12-17T21:18:43Z
Generation: 1
Resource Version: 248412
Self Link: /apis/app.example.com/v1alpha1/namespaces/myproject/appservices/example-appservice
UID: 554f301f-0241-11e9-b551-080027c7d133
Spec:
Size: 3
# Cleanup
$ kubectl delete -f deploy/crds/app.example.com_v1alpha1_appservice_cr.yaml
$ kubectl delete -f deploy/operator.yaml
$ kubectl delete -f deploy/role.yaml
$ kubectl delete -f deploy/role_binding.yaml
$ kubectl delete -f deploy/service_account.yaml
$ kubectl delete -f deploy/crds/app.example.com_appservices_crd.yaml