这里我们仅介绍ansible operator的开发
准备:
- 首先安装operator-sdk
- 有一个k8 cluster并且有cluster-admin的权限
- 一个image resigry, 如 hub.docker.com, quay.io
开始:
我们将创建一个简单的project, 来学习相关的流程
1. 创建一个project
- mkdir memcached-operator
- cd memcached-operator
- operator-sdk init --plugins=ansible --domain docker.hub.com
查看生成的本地目录为
2.创建memcached api
operator-sdk create api --group cache --version v1alpha1 --kind Memcached --generate-role
执行完成后,我们看到project, watches, roles, config 等文件更新了
3.编辑manager
vi roles/memcached/tasks/main.yml
使其内容为
- ---
- # tasks file for Memcached
- - name: start memcached
- kubernetes.core.k8s:
- definition:
- kind: Deployment
- apiVersion: apps/v1
- metadata:
- name: '{{ ansible_operator_meta.name }}-memcached'
- namespace: '{{ ansible_operator_meta.namespace }}'
- spec:
- replicas: "{{size}}"
- selector:
- matchLabels:
- app: memcached
- template:
- metadata:
- labels:
- app: memcached
- spec:
- containers:
- - name: memcached
- command:
- - memcached
- - -m=64
- - -o
- - modern
- - -v
- image: "docker.io/memcached:1.4.36-alpine"
- ports:
- - containerPort: 11211
可以看到,这个task的作用是定义个dc并定义了replicas。
实际上,这个task就是定义culster资源和状态的文件。
4. 为manager变量设置值
默认值
vi roles/memcached/defaults/main.yml
使其内容为
- ---
- # defaults file for Memcached
- size: 1
配置值
vi config/samples/cache_v1alpha1_memcached.yaml
使其内容为
- apiVersion: cache.hub.docker.com/v1alpha1
- kind: Memcached
- metadata:
- name: memcached-sample
- spec:
- # TODO(user): Add fields here
- size: 3
5. 更改makefile中的image tag
- 将 IMG ?= controller:latest
- 改为 IMG ?= $(IMAGE_TAG_BASE):$(VERSION)
6.编包并push
make docker-build docker-push IMG="cara/memcached-operator:v0.0.1"
7.运行bundle
operator-sdk run bundle docker.io/cara/memcached-operator:v0.0.1