GitLab CI/CD

Workflow

GitLab workflow example

准备工作

在开始使用 GitLab CI/CD 之前,我们需要完成以下准备工作。

  1. 安装 Gitlab 和 Gitlab Runer。
  2. 生成一对 SSH Private Key 和 SSH Public Key。

SSH Private Key 配置在 Setting > CI/CD > Variables 里面。

SSH Public Key 配置在要部署的服务器上的 ~/.ssh/authorized_keys 文件里面。


下面我们用两个例子来体验一下 GitLab CI / CD 配置文件 .gitlab-ci.yml 的语法。

PHP Examples

image: tanghengzhi/gitlab-deploy

before_script:
    # Add the private SSH key to the build environment
    - mkdir -p ~/.ssh
    - echo "$SSH_PRIVATE_KEY" > ~/.ssh/id_rsa
    - chmod 600 ~/.ssh/id_rsa
    - echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config

stages:
    - test
    - deploy

test:
    stage: test
    script: echo 'PHP is the best language in the world'
    only:
        - master

deploy-dev-and-test:
    stage: deploy
    script:
        # Run git pull
        - ssh ec2-user@54.223.162.119 sudo git -C /opt/case/woof-go-waybill pull
        - ssh ec2-user@54.223.162.119 sudo git -C /opt/case/woof-go-waybill-beta pull
    only:
        - master

deploy-online-1:
    stage: deploy
    script:
        # Run git pull
        - ssh ec2-user@54.222.244.71 sudo git -C /opt/case/waybill-service pull
    when: manual
    only:
        - master

deploy-online-2:
    stage: deploy
    script:
        # Run git pull
        - ssh ec2-user@52.81.109.73 sudo git -C /opt/case/waybill-service pull
    when: manual
    only:
        - master

Java Examples

image: tanghengzhi/gitlab-deploy:java

before_script:
    # Add the private SSH key to the build environment
    - mkdir -p ~/.ssh
    - echo "$SSH_PRIVATE_KEY" > ~/.ssh/id_rsa
    - chmod 600 ~/.ssh/id_rsa
    - echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config

stages:
    - build
    - deploy

build:
    stage: build
    script:
        - ./gradlew build
    artifacts:
        paths:
          - build/libs/*.jar
    only:
        - master

deploy-dev:
    stage: deploy
    script:
        - rsync build/libs/*.jar ec2-user@54.223.162.119:/opt/case/waybill-service/build/libs/
        - ssh ec2-user@54.223.162.119 sudo service waybill-service restart
    only:
        - master

参考:

https://docs.gitlab.com/ee/ci/introduction/index.html

https://docs.gitlab.com/ee/ci/

https://github.com/tanghengzhi/gitlab-deploy

 692 total views