← 返回首页

GitLab CI/CD实战

📂 java ⏱ 2 min 213 words

GitLab CI/CD实战

GitLab CI/CD是GitLab内置的持续集成工具,通过.gitlab-ci.yml配置实现全流程自动化。

基础配置

# .gitlab-ci.yml
image: maven:3.9-eclipse-temurin-17

stages:
  - build
  - test
  - package
  - deploy

variables:
  MAVEN_OPTS: "-Dmaven.repo.local=.m2/repository"

cache:
  key: ${CI_COMMIT_REF_SLUG}
  paths:
    - .m2/repository/

多阶段流水线

compile:
  stage: build
  script:
    - mvn compile -B
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
    - if: '$CI_COMMIT_BRANCH == "main"'

unit-test:
  stage: test
  script:
    - mvn test -B
  coverage: '/Total.*?(\d+\.\d+%)/'
  artifacts:
    when: always
    reports:
      junit:
        - target/surefire-reports/TEST-*.xml
      coverage_report:
        coverage_format: cobertura
        path: target/site/cobertura/coverage.xml

integration-test:
  stage: test
  services:
    - name: mysql:8.0
      alias: test-mysql
      variables:
        MYSQL_ROOT_PASSWORD: test
        MYSQL_DATABASE: testdb
  variables:
    DB_HOST: test-mysql
    DB_PORT: 3306
  script:
    - mvn verify -B -DskipUnitTests
  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'

package:
  stage: package
  script:
    - mvn package -DskipTests -B -Dmaven.artifact.transfer.version=2
  artifacts:
    paths:
      - target/*.jar
    expire_in: 1 week
  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'

docker-build:
  stage: package
  image: docker:latest
  services:
    - docker:dind
  before_script:
    - echo "$CI_REGISTRY_PASSWORD" | docker login -u "$CI_REGISTRY_USER" --password-stdin $CI_REGISTRY
  script:
    - docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA .
    - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'

变量与密钥管理

variables:
  # CI/CD变量在GitLab Settings > CI/CD > Variables中配置
  SONAR_HOST_URL: "https://sonar.example.com"

sonar-scan:
  stage: test
  script:
    - mvn sonar:sonar
      -Dsonar.host.url=$SONAR_HOST_URL
      -Dsonar.login=$SONAR_TOKEN
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'

多环境部署

deploy-staging:
  stage: deploy
  script:
    - kubectl config use-context staging
    - kubectl set image deployment/app app=$CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
  environment:
    name: staging
    url: https://staging.example.com
  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'

deploy-production:
  stage: deploy
  script:
    - kubectl config use-context production
    - kubectl set image deployment/app app=$CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
  environment:
    name: production
    url: https://www.example.com
  when: manual
  rules:
    - if: '$CI_COMMIT_BRANCH == "main"'

小结

GitLab CI/CD与代码仓库深度集成,通过.gitlab-ci.yml即可实现完整的自动化流水线。