最新消息:

gitlab内置CICD的使用

IT技术 ipcpu 55浏览 0评论

gitlab CICD.md

概述

GitLab内置了CI/CD工具,相比于Jenkins等工具,更加快捷和方便。

GitLab CI/CD由一个名为 .gitlab-ci.yml 的文件进行配置,该文件位于仓库的根目录下。

配置文件中指定的脚本由GitLab Runner执行。

GitLab Runner 有四种运行方式,Shell、DockerinDocker、DockerOutOfDocker、Kaniko四种方式,Kaniko是Google为了解决DinD和DooD的权限和安全性推出的工具,本站其他文章有介绍。

.gitlab-ci.yml文件样例

这里的Runner使用的是DooD模式。

image: golang:1.18

stages:
  - test
  - codesonarscan
  - dockerbuild
  - deploy

test:
  stage: test

  before_script:
    - go env -w GOPROXY=https://goproxy.cn,direct
    - go env -w GO111MODULE=on
  script:
    - echo "start test"
    - go test ./... -v >test.json

codesonarscan:
  stage: codesonarscan
  variables:
    SONAR_TOKEN: "TOKEN"
    SONAR_HOST_URL: "SONAR_SERVER"
    GIT_DEPTH: 0
  image: sonarsource/sonar-scanner-cli:latest
  script:
    - echo "start sonar scaning"
    - sonar-scanner -Dsonar.projectKey=PROJECT_NAME   -Dsonar.sources=.
  allow_failure: true

dockerbuild:
  stage: dockerbuild
  image: docker:stable
  before_script:
    - docker  info    
  script:
    - docker login user password 
    - docker  build -t reg.ipcpu.com/m/gohelloworld:${CI_PIPELINE_ID}-${CI_COMMIT_SHORT_SHA}  
    - docker      push  reg.ipcpu.com/m/gohelloworld:${CI_PIPELINE_ID}-${CI_COMMIT_SHORT_SHA}


deploy_staging:
  stage: deploy
  image: lwolf/kubectl_deployer:latest
  script:
    - kubectl version
    - cd k8s/
    - sed -i "s/__CI_BUILD_REF_SLUG__/${CI_PROJECT_NAME}-${CI_ENVIRONMENT_SLUG}/" deployment.yml 
    - sed -i "s/__VERSION__/${CI_PIPELINE_ID}-${CI_COMMIT_SHORT_SHA}/" deployment.yml
    - sed -i "s/__CI_REPL_NUMBER__/1/" deployment.yml
    - kubectl apply -f deployment.yml
    - kubectl rollout status -f deployment.yml
    - echo "Deploy to staging server"
  environment:
    name: staging
    url: https://staging.ipcpu.com
  only:
  - master


deploy_prod:
  stage: deploy
  image: lwolf/kubectl_deployer:latest
  script:
    - kubectl version
    - cd k8s/
    - sed -i "s/__CI_BUILD_REF_SLUG__/${CI_PROJECT_NAME}-${CI_ENVIRONMENT_SLUG}/" deployment.yml 
    - sed -i "s/__VERSION__/${CI_PIPELINE_ID}-${CI_COMMIT_SHORT_SHA}/" deployment.yml
    - sed -i "s/__CI_REPL_NUMBER__/4/" deployment.yml
    - kubectl apply -f deployment.yml
    - kubectl rollout status -f deployment.yml
    - echo "Deploy to production server"
  environment:
    name: production
    url: https://www.ipcpu.com
  when: manual
  only:
  - master

当项目代码更新后,CICD流程会自动执行:

如果想要手动操作某些过程,比如上线到生产环境,加上 when: manual 就可以了,效果如下:

转载请注明:IPCPU-网络之路 » gitlab内置CICD的使用

发表我的评论
取消评论
表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址