Operator最近越來越流行,它是CoreOS推出的旨在管理安裝k8s應用的技術框架, 屬於devops的範疇,你可以簡單理解爲一個Installer,熟悉k8s的同學可能馬上就會問,那置Helm於何地?你說對了,Operator就是來革Helm的命的!Operator其實說白了就是一個k8s CRD 和 Controller, 一般都是用Redhat推出的工具:Operator-sdk 來實現。
今天的並不想講太多的Operator,想介紹一個幫助快速實現Operator的開源項目:https://github.com/vincent-pli/operator-sample-kustomize
這個項目是大概想法是:
利用Template(yaml,Kustomize的結構)定義應用。引入Extension,定義安裝應用過程中的行爲。
模板(Template)
模板的默認路徑在template目錄下, 看看結構:
└── install
└── helloWorld
├── configMap.yaml
├── deployment.yaml
├── kustomization.yaml
├── namespace.yaml
└── service.yaml
install是CRD的名字,沒啥意義,忽略。
helloWorld是Component的名字,支持多個Component組成一個應用的情況。
注意Component需要在./deploy/operator.yaml中定義:
apiVersion: apps/v1
kind: Deployment
metadata:
name: operator-sample-kustomize
spec:
replicas: 1
selector:
matchLabels:
name: operator-sample-kustomize
template:
metadata:
labels:
name: operator-sample-kustomize
spec:
serviceAccountName: operator-sample-kustomize
containers:
- name: operator-sample-kustomize
# Replace this with the built image name
image: index.docker.io/vincentpli/operator-sample:v0.0.1
command:
- operator-sample-kustomize
imagePullPolicy: Always
env:
- name: WATCH_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
- name: OPERATOR_NAME
value: "operator-sample-kustomize"
- name: TEMPLATES_PATH
value: "/usr/local/templates"
- name: COMPONENTS
value: "helloworld"
多個Component使用逗號(,)隔開。
熟悉的同學應該看出來了helloWorld目錄下其實是Kustomize的配置文件。
擴展(Extension)
引入了Extension的概念,是把一些Optional的操作plugin化,讓這些操作可以方便的enable/disable。
先放一個CR的例子:
apiVersion: install.example.com/v1alpha1
kind: Install
metadata:
name: example-install
spec:
# Add fields here
targetNamespace: operator-sample
setowner: true
registry:
override:
the-container: monopole/hello:1
目前可用的Extension有:
- nsinject: 注入namespace,注意上面例子中的targetNamespace,如果這個字段存在,plugin:nsinject被激活,所有在template中的k8s resource都被設置爲namespace: operator-sample
- ownerset:設置resource的owner。上面例子中的setowner, 如果這字段被設置爲true,plugin: ownerset被激活,所有在template中的k8s resource的owner都被設置爲該CR: example-install
- imagereplacement:替換container中的image url。如上例子表明:template中resource裏面的名爲“the-container”的container中的image url被替換爲“monopole/hello:1”
實現新的Extension
實現一個新的Extension還是比較簡單的,先看項目結構:
./pkg/extension是extension實現的代碼。
./pkg/controller/install/add_* 是該extension被納入操作的代碼
具體實現請看代碼,比較簡單,一看便知。
該項目還有很多缺點,比如無UT,無文檔等等,有待後續加強。