利用GitLab进行Linux项目的持续集成(CI)和持续交付(CD)是一个相对直接的过程。以下是一个基本的步骤指南,帮助你设置和使用GitLab进行持续集成:
首先,你需要在Linux服务器上安装GitLab Runner。GitLab Runner是一个用于执行CI/CD任务的工具。
在Ubuntu上安装GitLab Runner:
sudo apt update
sudo apt install curl openssh-server policycoreutils-python
curl -L https://packages.gitlab.com/install/repositories/runner/gitlab-ci-multi-runner/script.deb.sh | sudo bash
sudo chmod x /usr/local/bin/gitlab-runner
sudo useradd --comment 'GitLab Runner' --create-home gitlab-runner --shell /bin/bash
sudo gitlab-runner install --user=gitlab-runner --working-directory=/home/gitlab-runner
在CentOS上安装GitLab Runner:
sudo yum update
sudo yum install curl openssh-server openssh-clients postfix cronie policycoreutils-Python
curl -L https://packages.gitlab.com/install/repositories/runner/gitlab-ci-multi-runner/script.rpm.sh | sudo bash
sudo chmod x /usr/local/bin/gitlab-runner
sudo gitlab-runner install --user=gitlab-runner --working-directory=/home/gitlab-runner
sudo gitlab-runner start
在GitLab的管理界面中,依次进入 Settings
- CI/CD
- Runners
,点击 Register a Runner
。按照提示输入GitLab实例的URL和注册令牌,选择执行器(如 shell
),然后保存。
.gitlab-ci.yml
文件在你的项目根目录下创建一个名为 .gitlab-ci.yml
的文件,该文件定义了CI/CD Pipeline的工作流程和任务。
示例配置:
stages:
- build
- test
- deploy
build_job:
stage: build
script:
- echo "Building your application here..."
test_job1:
stage: test
script:
- echo "This job tests something"
test_job2:
stage: test
script:
- echo "This job tests something, but takes more time than test_job1."
- sleep 20
deploy_job:
stage: deploy
script:
- echo "Deploying your application here..."
在GitLab项目的“Settings”页面,找到“CI/CD”选项,并配置Runner以及其他相关设置。确保启用CI/CD功能并保存。
将代码提交到GitLab仓库,并在GitLab界面上手动触发CI/CD Pipeline,或者配置Webhooks来自动触发Pipeline。
在GitLab界面上可以查看CI/CD Pipeline的执行结果,包括构建日志、测试结果等信息。
.gitlab-ci.yml
文件中,你可以定义变量和缓存,以便在构建过程中使用。通过以上步骤,你就可以在Linux上使用GitLab进行基本的持续集成了。根据你的项目需求,你可以进一步自定义 .gitlab-ci.yml
文件,添加更多的阶段和任务。