在Ubuntu上為Golang項目配置CI/CD(持續集成和持續部署)可以通過多種方式實現,其中最常用的是使用GitHub Actions、GitLab CI/CD或Jenkins。以下是使用GitHub Actions和GitLab CI/CD的示例步驟:
創建GitHub倉庫:
初始化Golang項目:
go.mod文件。創建GitHub Actions工作流文件:
.github/workflows目錄。ci.yml。name: CI
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.17
- name: Build
run: go build -v ./...
- name: Test
run: go test -v ./...
提交并推送工作流文件:
.github/workflows/ci.yml文件添加到你的倉庫并提交推送。配置GitHub Secrets(可選):
創建GitLab項目:
初始化Golang項目:
go.mod文件。創建.gitlab-ci.yml文件:
.gitlab-ci.yml文件。stages:
- build
- test
build:
stage: build
image: golang:1.17
script:
- go build -v ./...
artifacts:
paths:
- bin/
test:
stage: test
image: golang:1.17
script:
- go test -v ./...
提交并推送.gitlab-ci.yml文件:
.gitlab-ci.yml文件添加到你的倉庫并提交推送。配置GitLab CI/CD變量(可選):
如果你還需要配置持續部署(CD),可以在上述工作流文件中添加部署步驟。例如,使用SSH將構建好的二進制文件部署到遠程服務器:
deploy:
stage: deploy
image: appleboy/scp-action@master
with:
host: ${{ secrets.SSH_HOST }}
username: ${{ secrets.SSH_USERNAME }}
key: ${{ secrets.SSH_KEY }}
source: ./bin/your-app
target: /path/to/deploy
deploy:
stage: deploy
image: appleboy/scp-action@master
script:
- scp ./bin/your-app $SSH_USER@$SSH_HOST:/path/to/deploy
only:
- main
通過以上步驟,你可以在Ubuntu上為Golang項目配置CI/CD,并實現自動化構建、測試和部署。