IT七剑客 IT七剑客
首页
wresource
郭霖
孤寒者
IT邦德
沉默王二
老麦
stackoverflow
GitHub (opens new window)
首页
wresource
郭霖
孤寒者
IT邦德
沉默王二
老麦
stackoverflow
GitHub (opens new window)
  • 从零开始写 k8s 发布工具(一)

  • 从零开始写 k8s 发布工具(二)

    • 模仿 kubectl create 创建 Deployment 样例
    • 从零开始写 k8s 发布工具 - 2.2. 定义字符串创建 Service
    • 解析 URL 为 Ingress
    • 使用 kustomize 管理所有 k8s 文件
      • Kustomize
      • 编码
      • 其它
      • 测试
    • 使用 cobra 实现 kustz 命令
  • 从零开始写 k8s 发布工具(三)

  • 从零开始写 k8s 发布工具(四)

  • istio的环境准备

  • istioVirtualService

  • 老麦 Go
  • 从零开始写 k8s 发布工具(二)
老麦
2023-01-31
目录

使用 kustomize 管理所有 k8s 文件

# 2.4. 使用 kustomize 管理所有 k8s 文件

logo

前面已经简单的封装了 Deployment, Service, Ingress, 完成了零部件的创建。

今天就通过 Kustomization 进行组装, 实现流水线。

# Kustomize

开始之前, 先来安装 kustomize 库。

$ go get sigs.k8s.io/kustomize/v3
1

这里补充一下, 访问 Github https://github.com/kubernetes-sigs/kustomize/。

kustomize () 首页 README.md 并没有提到 go get 的包名。 通常 k8s 的代码在 github 上都是镜像。 这时候只需要进到 go.mod , 包名就一目了然。

// go.mod
module sigs.k8s.io/kustomize/v3

go 1.12
1
2
3
4

# 编码

先来看看 kustomization.yml 的定义, 非常的简单。

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: demo-demo
resources:
  - deployment.yml
  - service.yml
  - ingress.yml
1
2
3
4
5
6
7

今天的代码及其简单, 只需要 20 行搞定。 在 import 的时候, 可能自动补全不会自己带上 v3。 需要手工调整一下。

package kustz

import "sigs.k8s.io/kustomize/v3/pkg/types"

func (kz *Config) Kustomization() types.Kustomization {
	k := types.Kustomization{
		TypeMeta: types.TypeMeta{
			Kind:       types.KustomizationKind,
			APIVersion: types.KustomizationVersion,
		},
		Namespace: kz.Namespace,
		Resources: []string{
			"deployment.yml",
			"service.yml",
			"ingress.yml",
		},
	}

	return k
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

这里已经定了 kustomization 三个外部资源名字。

# 其它

kustomize 还是很贴心的, 在 types 把 version 和 kind 已经通过常量定义好了。

在 https://github.com/kubernetes-sigs/kustomize/blob/v3.3.1/pkg/types/kustomization.go

const (
	KustomizationVersion = "kustomize.config.k8s.io/v1beta1"
	KustomizationKind    = "Kustomization"
)
1
2
3
4

另外我们可以看到, 虽然 TypeMeta 定义相同, 但是直接从 apimachinery/pkg/apis/meta/v1.TypeMeta 复制过来的, 而不是通过引用。

// TypeMeta partially copies apimachinery/pkg/apis/meta/v1.TypeMeta
// No need for a direct dependence; the fields are stable.
type TypeMeta struct {
	Kind       string `json:"kind,omitempty" yaml:"kind,omitempty"`
	APIVersion string `json:"apiVersion,omitempty" yaml:"apiVersion,omitempty"`
}
1
2
3
4
5
6

之前看到一句话, 简单的拷贝比引用可能更节约资源, 因为引用是初始化一整个包

# 测试

执行命令, 检查结果是不是和自己期待的一样。

$ go test -timeout 30s -run ^Test_KustzKustomize$ ./pkg/kustz/ -v
1

如果不是, 就回去检查代码吧。

编辑 (opens new window)
上次更新: 2023/02/05, 02:48:13
解析 URL 为 Ingress
使用 cobra 实现 kustz 命令

← 解析 URL 为 Ingress 使用 cobra 实现 kustz 命令→

最近更新
01
Coding 102 Writing code other people can read
02-26
02
Kotlin Flow响应式编程,StateFlow和SharedFlow
02-05
03
Kotlin Flow响应式编程,操作符函数进阶
02-05
更多文章>
Theme by Vdoing | Copyright © 2022-2023 IT七剑客 | MIT License
  • 闽ICP备2021006579号-4
  • 闽公网安备 35012102500470号
    • 跟随系统
    • 浅色模式
    • 深色模式
    • 阅读模式