DevOps CI/CD 分析(四)之编写K8S yaml模版


本文摘自网络,作者,侵删。

本节我们开始编写K8S yaml模版文件,如果对K8S yaml模版配置不清楚的请参阅DevOps CI/CD 分析(三)之K8S yaml模版配置详解,DevOps CI/CD的整个过程中,我们会依赖我们的K8S yaml模版文件,每个项目中只需要配置项目相关的参数,最终会将项目中配置的参数替换到K8S yaml模版文件中,现在我们直接开始进入主题!


Kubernetes yaml模版内容

{{$defaultPort := "80"}}
{{$contrainerPort := or .contrainerPort $defaultPort}}
{{$isService := eq (or .notService "false") "false"}}
{{$isProd := eq .env "prod"}}
{{$isOpenSkywalking := eq (or .isOpenSkywalking "false") "true"}}
{{$isEnableSkywalking := or (or $isProd $isOpenSkywalking) "false"}}

{{if $isService}}
apiVersion: v1
kind: Service
metadata:
  name: {{.appName}}
  namespace: {{.namespace}}
  labels:
    app: {{.appName}}
spec:
  ports:
  - port: 80
    name: http
    targetPort: {{$contrainerPort}}
  - port: 443
    name: https
    targetPort: {{$contrainerPort}}
  selector:
    app: {{.appName}}
{{end}}
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: {{.appName}}
  namespace: {{.namespace}}
spec:
  replicas: {{.replicas}}
  minReadySeconds: {{.minReadySeconds}}
  strategy:
    rollingUpdate:
      maxSurge: 2
      maxUnavailable: 1
  selector:
    matchLabels:
      app: {{.appName}}
  template:
    metadata:
      labels:
        app: {{.appName}}
        version: "{{.version}}"
        deployDate: "{{.deployDate}}"
    spec:
      terminationGracePeriodSeconds: 60
      {{if $isEnableSkywalking}}
      initContainers:
        - command:
            - cp
            - '-r'
            - /skywalking/agent/
            - /data/agents/skywalking/
          image: 'registry.cn-beijing.aliyuncs.com/company/skywalking-agent:6.2.0-v1.3-60'
          imagePullPolicy: Always
          name: init-skywalking
          resources: {}
          terminationMessagePath: /dev/termination-log
          terminationMessagePolicy: File
          volumeMounts:
            - mountPath: /data/agents/
              name: init
      {{end}}
      containers:
      - name: {{.appName}}
        image: {{.image}}:{{.version}}
        imagePullPolicy: Always
        args: ["--spring.profiles.active={{.env}}"]
        env:
          {{if .javaOpts}}
          - name: JAVA_OPTS
            value: "{{.javaOpts}}"
          {{end}}
          {{if .ramPercentage}}
          - name: RAMPERCENTAGE
            value: "{{.ramPercentage}}"
          {{end}}
          {{if $isEnableSkywalking}}
          - name: SKYWALKING_NAME
            value: {{.appName}}
          - name: SKYWALKING_BACKEND_SERVICE
            valueFrom:
              #从kind: Secret资源中获取秘钥管理,主要为了避免重要信息暴露
              secretKeyRef:
                name: secret-skywalking
                key: backend_services
          - name: SKYWALKING_AUTHENTICATION
            valueFrom:
              #从kind: Secret资源中获取秘钥管理,主要为了避免重要信息暴露
              secretKeyRef:
                name: secret-skywalking
                key: authentication
        resources:
          requests:
            {{if .request_cpu}}
            #2核2线程的CPU,被系统识别为4个逻辑CPU,request_cpu=200表示0.2个逻辑cpu
            cpu: {{.request_cpu}}m
            {{end}}
            memory: {{.request_memory}}Mi
          limits:
            memory: {{.limit_memory}}Mi
        {{if $hasService}}
        ports:
        - name: http
          containerPort: {{$contrainerPort}}
        {{end}}
        volumeMounts:
        - name: config-volume
          mountPath: /data/config/
        - name: init
          mountPath: /data/agents/
        {{if .healthPath}}
        livenessProbe:
          httpGet:
            path: {{.healthPath}}
            port: {{$contrainerPort}}
            scheme: HTTP
          initialDelaySeconds: 60
          periodSeconds: 10
          timeoutSeconds: 5
          successThreshold: 1
          failureThreshold: 5
        readinessProbe:
          httpGet:
            path: {{.healthPath}}
            port: {{$contrainerPort}}
            scheme: HTTP
          initialDelaySeconds: 60
          timeoutSeconds: 5
          successThreshold: 1
          failureThreshold: 5
        {{end}}
      imagePullSecrets:
      - name: ali-docker-registry-vpc
      {{if .registry}}
      - name: {{.registry}}
      {{end}}
      volumes:
      - name: config-volume
        configMap:
          defaultMode: 420
          name: {{.appName}}-config
          optional: true
      - name: init
        emptyDir: {}
{{if .targetCPUUtilizationPercentage}}
---
apiVersion: autoscaling/v1
kind: HorizontalPodAutoscaler
metadata:
  name: {{.appName}}-hpa
  namespace: {{.namespace}}
spec:
  maxReplicas: {{.maxReplicas}}
  minReplicas: {{.minReplicas}}
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: {{.appName}}
  targetCPUUtilizationPercentage: {{.targetCPUUtilizationPercentage}}
{{end}}

这个模版文件的内容就如大家所见到的,看起来特别复杂,所以按老规矩流程,我们还是讲解下大致的配置代表什么意思,如果没有任何Kubernetes yaml模版基础的话,可以转至DevOps CI/CD 分析(三)之K8S yaml模版配置详解章节先看看大概用法。


GoLang模版语法

我们看到代码块中出现了很多{{...}}这样的表达式,这个是基于GoLang的模版写法,我们使用的是GoLang中html/template模版库,那么我们就简单介绍下模版用法。外部传入的参数格式为{{.参数}}

//如果传入了外部参数condition1或者condition2,则执行
//当.condition*为bool类型的时候,为true表示执行,当.condition*为string类型的时候,非空表示执行
{{if or .condition1 .condition2}}
......
{{end}}
//如果condition1和condition2相等,则执行
{{if eq .condition1 .condition2}}
......
{{end}}
  1. {{$defaultPort := "80"}} 我们定义了一个默认端口变量defaultPort,默认值为80
  2. {{$contrainerPort := or .contrainerPort $defaultPort}} 定义一个容器端口变量contrainerPort,or 代表或者的意思,如果.contrainerPort => 外部传入contrainerPort变量则使用,否则使用默认的defaultPort端口。
  3. {{$isService := eq (or .notService "false") "false"}} 定义一个是否有服务的标志变量isService,eq 代表相等的意思,(or .notService "false") 这个整体的值是否等于false,所以当外部传入notService变量,那么(or .notService "false")整体的值就为true,则isService就是false,默认notService传入,isService默认为true。
  4. {{$isProd := eq .env "prod"}},是否为prod生产环境,根据外部传入的env变量进行判断
  5. {{$isOpenSkywalking := eq (or .isOpenSkywalking "false") "true"}},是否打开Skywalking链路追踪的开关,默认为false。
  6. {{$isEnableSkywalking := or (or $isProd $isOpenSkywalking) "false"}},是否启用Skywalking链路追踪,默认在生产环境为true。

Kubernetes yaml模版讲解

默认情况下,我们定义的Kubernetes yaml模版会包括两种Kubernetes资源,kind: Service与kind: Deployment,Service与Deployment的关系这里我们也不过多讲解(Service通过labels标签找到Deployment下面的Pod),这个资源里面我们还看到有一个kind: HorizontalPodAutoscaler,这个就是HPA,根据设置的CPU利用率自动伸缩 ReplicationController、ReplicaSet、Deployment、 StatefulSet中的pod数量。

spec:
  template:
    spec:
      {{if $isEnableSkywalking}}
      initContainers:
          #执行cp -r /skywalking/agent/ /data/agents/skywalking/
          #拷贝我们skywalking源码目录到容器内的指定目录
        - command:
            - cp
            - '-r'
            - /skywalking/agent/
            - /data/agents/skywalking/
          #容器的镜像名称
          image: 'registry.cn-beijing.aliyuncs.com/company/skywalking-agent:6.2.0-v1.3-60'
          #每次都会重新下载镜像
          imagePullPolicy: Always
          name: init-skywalking
          resources: {}
          #容器挂掉之后的相关log写入的目录
          terminationMessagePath: /dev/termination-log
          #官方写法,类型File
          terminationMessagePolicy: File
          #挂载到容器内部的存储卷配置
          volumeMounts:
              #存储卷在容器内mount的绝对路径
            - mountPath: /data/agents/
              #引用spec.template.volumes定义的共享存储卷的名称
              name: init
      {{end}}
      #定义共享存储卷列表(emptyDir、hostPath、secret、configMap类型)
      #hostPath类型的存储卷,表示挂载Deployment-Pod所在宿主机的目录
      #secret类型的存储卷,挂载集群与定义的secret对象到容器内部
      volumes:
        #共享存储卷名称
      - name: config-volume
        #configMap类型的存储卷,挂载预定义的configMap对象到容器内部
        configMap:
          #挂载容器内部的文件的权限,0到0777
          defaultMode: 420
          #kind: ConfigMap资源类型,比如我们在阿里云的容器服务-Kubernetes=>应用配置=>配置项中创建的
          name: {{.appName}}-config
          optional: true
        #共享存储卷名称
      - name: init
        #emtyDir类型的存储卷,与Deployment-Pod同一个生命周期的临时目录
        emptyDir: {}

如果我们开启了Skywalking的链路追踪,那么我们需要配置initContainers,在容器初始化阶段配置我们Skywalking相关的配置,下面看看自动伸缩相关的配置。

{{if .targetCPUUtilizationPercentage}}
---
apiVersion: autoscaling/v1
#HPA资源
kind: HorizontalPodAutoscaler
metadata:
  #名称
  name: {{.appName}}-hpa
  #命令空间
  namespace: {{.namespace}}
spec:
  #最大副本数(Pod数量)
  maxReplicas: {{.maxReplicas}}
  #最小副本数(Pod数量)
  minReplicas: {{.minReplicas}}
  #需要伸缩的目标资源
  scaleTargetRef:
    apiVersion: apps/v1
    #监控类型
    kind: Deployment
    #监控名为{{.appName}}的Deployment
    name: {{.appName}}
  #监控的Cpu阈值
  targetCPUUtilizationPercentage: {{.targetCPUUtilizationPercentage}}
{{end}}

本节的Kubernetes yaml模版内容已经总结完毕,模版内容会在后续的章节中使用,我们在后续的章节中,会在gitlab-ci.yml中使用GoLang程序对模版内容进行替换,然后使用kubectl apply -f deploy.yml 相关命令创建Kubernetes相关的资源。


本文来自:简书

感谢作者:Blog

查看原文:DevOps CI/CD 分析(四)之编写K8S yaml模版

相关阅读 >>

Golang会代替java吗?

Go语言 if…else 语句

搭建vscode Golang开发环境

djanGo模板语言

锁的使用场景主要涉及到哪些?读写锁为什么会比普通锁快【Golang 入门系列十六】

dubbo-Go 应用维度注册模型

最新字节跳动面试题与岗位层级,绩效考核制度介绍

Golang语言社区投稿】Golang高并发基于协程,通道的任务池

Go语言入门-1 环境搭建

使用 Google/wire 对 Go 项目进行依赖注入

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...