【云原生与DevOps】05-GitOps工作流:ArgoCD+GitHub Actions完整方案
·
专栏: 云原生 & DevOps
难度: 进阶
标签: GitOps ArgoCD GitHub Actions K8s 自动化部署
前言
GitOps 的核心思想:Git 是唯一事实来源,所有变更都通过 Git PR 触发。本文实现一套完整的 GitOps 流水线。
一、架构设计
开发者 push 代码
↓
GitHub Actions(CI)
- 构建镜像
- 推送到 Registry
- 更新 GitOps 仓库中的镜像 tag
↓
ArgoCD(CD)
- 监控 GitOps 仓库变化
- 自动同步到 K8s 集群
二、安装 ArgoCD
kubectl create namespace argocd
kubectl apply -n argocd -f \
https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml
# 等待Pod就绪
kubectl wait --for=condition=available \
deployment/argocd-server -n argocd --timeout=300s
# 获取初始密码
kubectl -n argocd get secret argocd-initial-admin-secret \
-o jsonpath="{.data.password}" | base64 -d
# 暴露UI(开发用)
kubectl port-forward svc/argocd-server -n argocd 8080:443
三、创建 ArgoCD Application
# argocd-app.yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: myapp-production
namespace: argocd
spec:
project: default
source:
repoURL: https://github.com/yourorg/gitops-configs.git
targetRevision: main
path: apps/myapp/overlays/production
destination:
server: https://kubernetes.default.svc
namespace: production
syncPolicy:
automated:
prune: true # 自动删除Git中不存在的资源
selfHeal: true # 检测到集群状态与Git不符时自动修复
syncOptions:
- CreateNamespace=true
四、GitHub Actions 工作流
# .github/workflows/ci-cd.yml
name: CI/CD Pipeline
on:
push:
branches: [main]
pull_request:
branches: [main]
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
GITOPS_REPO: yourorg/gitops-configs
jobs:
build-and-push:
runs-on: ubuntu-latest
outputs:
image-tag: ${{ steps.meta.outputs.version }}
steps:
- uses: actions/checkout@v4
- name: Docker meta
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=sha,prefix=,suffix=,format=short
- name: Build and push
uses: docker/build-push-action@v5
with:
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
update-gitops:
needs: build-and-push
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
repository: ${{ env.GITOPS_REPO }}
token: ${{ secrets.GITOPS_TOKEN }}
- name: Update image tag
run: |
cd apps/myapp/overlays/production
sed -i "s|newTag:.*|newTag: ${{ needs.build-and-push.outputs.image-tag }}|" kustomization.yaml
- name: Commit and push
run: |
git config user.email "ci@example.com"
git config user.name "CI Bot"
git add .
git commit -m "ci: update myapp to ${{ needs.build-and-push.outputs.image-tag }}"
git push
五、回滚操作
# 通过ArgoCD UI或命令行回滚
argocd app history myapp-production
argocd app rollback myapp-production <REVISION>
# 或者通过Git回滚(推荐,有记录)
git revert HEAD
git push
结语: GitOps 最大的价值是审计性——所有变更都有 Git 记录,随时可以追溯谁在什么时候改了什么。这对于合规要求高的场景非常重要。
更多推荐

所有评论(0)