【云原生与DevOps】05-GitOps工作流:ArgoCD+GitHub Actions完整方案

📅 2026/7/1 1:28:58
【云原生与DevOps】05-GitOps工作流:ArgoCD+GitHub Actions完整方案
专栏云原生 DevOps难度进阶标签GitOpsArgoCDGitHub ActionsK8s自动化部署前言GitOps 的核心思想Git 是唯一事实来源所有变更都通过 Git PR 触发。本文实现一套完整的 GitOps 流水线。一、架构设计开发者 push 代码 ↓ GitHub ActionsCI - 构建镜像 - 推送到 Registry - 更新 GitOps 仓库中的镜像 tag ↓ ArgoCDCD - 监控 GitOps 仓库变化 - 自动同步到 K8s 集群二、安装 ArgoCDkubectl create namespace argocd kubectl apply-nargocd-f\https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml# 等待Pod就绪kubectlwait--forconditionavailable\deployment/argocd-server-nargocd--timeout300s# 获取初始密码kubectl-nargocd get secret argocd-initial-admin-secret\-ojsonpath{.data.password}|base64-d# 暴露UI开发用kubectl port-forward svc/argocd-server-nargocd8080:443三、创建 ArgoCD Application# argocd-app.yamlapiVersion:argoproj.io/v1alpha1kind:Applicationmetadata:name:myapp-productionnamespace:argocdspec:project:defaultsource:repoURL:https://github.com/yourorg/gitops-configs.gittargetRevision:mainpath:apps/myapp/overlays/productiondestination:server:https://kubernetes.default.svcnamespace:productionsyncPolicy:automated:prune:true# 自动删除Git中不存在的资源selfHeal:true# 检测到集群状态与Git不符时自动修复syncOptions:-CreateNamespacetrue四、GitHub Actions 工作流# .github/workflows/ci-cd.ymlname:CI/CD Pipelineon:push:branches:[main]pull_request:branches:[main]env:REGISTRY:ghcr.ioIMAGE_NAME:${{github.repository}}GITOPS_REPO:yourorg/gitops-configsjobs:build-and-push:runs-on:ubuntu-latestoutputs:image-tag:${{steps.meta.outputs.version}}steps:-uses:actions/checkoutv4-name:Docker metaid:metauses:docker/metadata-actionv5with:images:${{env.REGISTRY}}/${{env.IMAGE_NAME}}tags:|typesha,prefix,suffix,formatshort-name:Build and pushuses:docker/build-push-actionv5with:push:${{github.event_name!pull_request}}tags:${{steps.meta.outputs.tags}}update-gitops:needs:build-and-pushif:github.ref refs/heads/mainruns-on:ubuntu-lateststeps:-uses:actions/checkoutv4with:repository:${{env.GITOPS_REPO}}token:${{secrets.GITOPS_TOKEN}}-name:Update image tagrun:|cd apps/myapp/overlays/production sed -i s|newTag:.*|newTag: ${{ needs.build-and-push.outputs.image-tag }}| kustomization.yaml-name:Commit and pushrun:|git config user.email ciexample.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 apphistorymyapp-production argocd app rollback myapp-productionREVISION# 或者通过Git回滚推荐有记录gitrevert HEADgitpush结语GitOps 最大的价值是审计性——所有变更都有 Git 记录随时可以追溯谁在什么时候改了什么。这对于合规要求高的场景非常重要。