在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,并实现自动化构建、测试和部署。