最近朋友接了一个外包,这家外包公司用gitlab来做cicd,朋友之前自动化部署基本上都是利用jenkins,没接触过过gitlab的cicd,朋友他对技术也是比较有追求,他发现这家公司k8s的yaml文件,很多字段其实可以抽出来,配合cicd动态传入,而不是把那些字段直接写死在yaml文件,比如docker镜像。刚好我之前也玩过一阵子基于gitlab的cicd,他就问我有没有什么思路,于是就有了本篇的写文素材
可以查看官网链接,如下
docs.gitlab.com/ee/ci/README.html
a、envsubst的作用
这个命令可以把环境变量传递给文件,并实现文件的变量替换,要替换的变量格式$ {var}或$ var
b、envsubst如何使用
echo '{{$HOME}}' | envsubst
envsubst < {{path/to/input_file}}
envsubst < {{path/to/input_file}} > {{path/to/output_file}}
envsubst '{{$USER $SHELL $HOME}}' < {{path/to/input_file}}
上述命令内容来自如下博文,因为命令没有几行,我就也贴了上来
blog.csdn.net/oopxiajun2011/article/details/111668011
注: 在mac上,需要安装gettext,才能使用envsubst
c、如何利用envsubst替换k8s deployment.ymal
假设deployment.ymal有个镜像内容形如下
image: $DEPLOY_PROCJECT_IMAGE
我们可以执行如下命令
envsubst < deployment.yml | kubectl apply -f -
这行命令的意思就是读取deployment.yml,并通过envsubst 把deployment.yml中的$DEPLOY_PROCJECT_IMAGE替换成相应的环境变量,并通过管道,把deployment.yml的内容传递给kubectl
示例:
注: 朋友的公司采用业务服务和部署服务.gitlab-ci.yml隔离,业务服务.gitlab-ci.yml通过触发部署服务的触发器进行部署,示例只列和本文相关的内容,其他配置信息做了清理
1、业务服务的.gitlab-ci.yml配置如下
variables: REGISTRY: xxx.docker.com PROJECTNAME: hello-demo IMAGE: demo/hello-demo DEPLOY_VERSION: $CI_COMMIT_TIMESTAMP stages: - triggerDeploy triggerDeployK8S: stage: triggerDeploy image: $REGISTRY/devops/busyboxplus:curl script: - curl -X POST -F token=fc4754200aa027baedf97cf7d45a02 -F ref=master -F "variables[DEPLOY_PROJECT_NAME]=$PROJECTNAME" -F "variables[DEPLOY_PROCJECT_IMAGE]=$REGISTRY/$IMAGE:dev" -F "variables[DEPLOY_VERSION]=$DEPLOY_VERSION" http://xxx.gitlab.com/api/v4/projects/32/trigger/pipeline only: - dev tags: - dev
其中
variables[DEPLOY_PROCJECT_IMAGE]=$REGISTRY/$IMAGE:dev
就是环境变量
2、部署服务的.gitlab-ci.yml配置如下
stages: - deploy deploy: stage: deploy script: - echo $DEPLOY_PROJECT_NAME - echo $DEPLOY_PROCJECT_IMAGE - echo $DEPLOY_VERSION - cd ${DEPLOY_PROJECT_NAME} - envsubst < deployment.yml | kubectl apply -f only: - triggers tags: - dev-deploy
3、deployment.yml示例
apiVersion: v1 kind: Service metadata: namespace: dev name: hello-demo spec: selector: app: hello-demo ports: - protocol: TCP port: 8080 targetPort: 8080 nodePort: 30011 type: NodePort sessionAffinity: ClientIP sessionAffinityConfig: clientIP: timeoutSeconds: 10800 --- apiVersion: apps/v1 kind: Deployment metadata: namespace: dev name: hello-demo labels: app: hello-demo spec: replicas: 3 selector: matchLabels: app: hello-demo template: metadata: labels: app: hello-demo spec: imagePullSecrets: - name: default-secret containers: - name: hello-demo image: $DEPLOY_PROCJECT_IMAGE imagePullPolicy: Always ports: - containerPort: 8080 env: # k8s滚动更新pod,是根据deployment.yml的变化来更新,如果代码更新了,但是deployment.yml内容没更新,k8s会认为 #pod没有产生变化,因此就不会进行滚动升级。DEPLOY_VERSION是用来做每次部署动态更新deployment.yml内容 - name: DEPLOY_VERSION value: "$DEPLOY_VERSION"
貌似也没啥内容总结,就贴个gitlab ci内置的variables文档作为总结吧