ArgoCD GitOps持续部署实战:Kubernetes应用自动同步与回滚配置方案

ArgoCD是CNCF毕业的GitOps持续交付工具,通过监听Git仓库变更自动同步Kubernetes集群状态,实现声明式部署与环境一致性。相比传统CI/CD推送模式,ArgoCD采用集群内拉取模式,无需向Kubernetes API暴露凭据。本文从安装部署到Application配置、同步策略、多环境管理,给出完整的GitOps流水线搭建方案。

ArgoCD安装部署与访问配置

通过kubectl在Kubernetes集群中安装ArgoCD:

# 创建命名空间并安装ArgoCD
kubectl create namespace argocd
kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml

# 查看Pod状态
kubectl get pods -n argocd -w

# 获取初始管理员密码
kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath="{.data.password}" | base64 -d

# 通过port-forward访问Web UI
kubectl port-forward svc/argocd-server -n argocd 8080:443

# 使用argocd CLI登录
argocd login localhost:8080 --username admin --password <初始密码>
argocd account update-password

生产环境配置Ingress暴露服务:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: argocd-ingress
  namespace: argocd
  annotations:
    nginx.ingress.kubernetes.io/backend-protocol: HTTPS
    nginx.ingress.kubernetes.io/ssl-passthrough: "true"
spec:
  rules:
  - host: argocd.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: argocd-server
            port:
              number: 443

Git仓库结构设计与Kustomize配置组织

GitOps模式下,Git仓库是应用部署的唯一真实来源。推荐目录结构:

gitops-repo/
├── apps/
│   ├── api-server/
│   │   ├── base/
│   │   │   ├── deployment.yaml
│   │   │   ├── service.yaml
│   │   │   ├── configmap.yaml
│   │   │   └── kustomization.yaml
│   │   └── overlays/
│   │       ├── dev/
│   │       │   ├── kustomization.yaml
│   │       │   └── patch-replicas.yaml
│   │       ├── staging/
│   │       │   ├── kustomization.yaml
│   │       │   └── patch-resources.yaml
│   │       └── production/
│   │           ├── kustomization.yaml
│   │           └── patch-production.yaml
│   └── web-frontend/
│       └── ...
└── argocd-apps/
    ├── api-server-dev.yaml
    ├── api-server-prod.yaml
    └── web-frontend-prod.yaml

Kustomize base的deployment.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: api-server
  labels:
    app: api-server
spec:
  replicas: 2
  selector:
    matchLabels:
      app: api-server
  template:
    metadata:
      labels:
        app: api-server
    spec:
      containers:
      - name: api-server
        image: registry.example.com/api-server:latest
        ports:
        - containerPort: 8080
        env:
        - name: APP_ENV
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        resources:
          requests:
            cpu: 100m
            memory: 256Mi
          limits:
            cpu: 500m
            memory: 512Mi
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 15
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /ready
            port: 8080
          initialDelaySeconds: 5
          periodSeconds: 5

生产环境overlay覆盖副本数和资源配置:

# apps/api-server/overlays/production/kustomization.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: production
resources:
- ../../base
patches:
- path: patch-production.yaml

# patch-production.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: api-server
spec:
  replicas: 6
  template:
    spec:
      containers:
      - name: api-server
        resources:
          requests:
            cpu: 500m
            memory: 512Mi
          limits:
            cpu: 2000m
            memory: 2Gi

Application创建与自动同步策略配置

通过ArgoCD Application CRD声明应用同步规则:

apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: api-server-production
  namespace: argocd
  finalizers:
  - resources-finalizer.argocd.argoproj.io
spec:
  project: production
  source:
    repoURL: https://github.com/org/gitops-repo
    targetRevision: main
    path: apps/api-server/overlays/production
  destination:
    server: https://kubernetes.default.svc
    namespace: production
  syncPolicy:
    automated:
      prune: true
      selfHeal: true
      allowEmpty: false
    syncOptions:
    - CreateNamespace=true
    - PrunePropagationPolicy=foreground
    - PruneLast=true
    retry:
      limit: 5
      backoff:
        duration: 5s
        factor: 2
        maxDuration: 3m

关键配置说明:

  • prune: true:Git中删除的资源在集群中也删除
  • selfHeal: true:集群中被手动修改的资源自动恢复到Git声明的状态
  • PrunePropagationPolicy: foreground:删除资源时等待关联资源级联完成
  • retry:同步失败自动重试,指数退避策略

使用App of Apps模式管理多个应用:

apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: production-apps
  namespace: argocd
spec:
  project: default
  source:
    repoURL: https://github.com/org/gitops-repo
    path: argocd-apps
    targetRevision: main
  destination:
    server: https://kubernetes.default.svc
    namespace: argocd
  syncPolicy:
    automated:
      prune: true
      selfHeal: true

ArgoCD会自动扫描argocd-apps目录下的所有Application YAML,创建并管理子应用。

多环境部署与版本回滚操作

ArgoCD通过Git分支或目录区分环境。开发环境跟踪main分支,生产环境锁定特定tag或commit:

# 开发环境Application
spec:
  source:
    targetRevision: main

# 生产环境Application(锁定tag)
spec:
  source:
    targetRevision: v1.2.3

镜像更新通过ArgoCD Image Updater自动同步Git:

# 安装argocd-image-updater
kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj-labs/argocd-image-updater/stable/manifests/install.yaml

# Application添加镜像更新注解
metadata:
  annotations:
    argocd-image-updater.argoproj.io/image-list: api-server=registry.example.com/api-server
    argocd-image-updater.argoproj.io/api-server.update-strategy: semver
    argocd-image-updater.argoproj.io/write-back-method: git
    argocd-image-updater.argoproj.io/git-branch: main

镜像更新后,Image Updater自动修改Git仓库中的镜像tag并提交,ArgoCD检测到Git变更后触发同步。

版本回滚操作:

# 方法1:Git回滚(推荐)
git revert <commit-hash>
git push origin main
# ArgoCD自动检测变更并同步

# 方法2:ArgoCD CLI回滚
argocd app rollback api-server-production <revision-id>

# 方法3:手动暂停自动同步后回滚
argocd app set api-server-production --sync-policy none
argocd app history api-server-production
argocd app rollback api-server-production <history-id>
# 回滚验证后恢复自动同步
argocd app set api-server-production --sync-policy automated

同步状态监控与告警配置

ArgoCD内置Prometheus指标暴露,集成监控告警:

# ArgoCD metrics端口默认在9090/9091
# Prometheus ServiceMonitor配置
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: argocd
  namespace: argocd
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: argocd-server-metrics
  endpoints:
  - port: metrics
    interval: 30s

关键监控指标:

# 应用同步状态
argocd_app_info{sync_status!="Synced"}  # 未同步的应用
argocd_app_info{health_status!="Healthy"}  # 健康状态异常

# 同步操作统计
rate(argocd_app_sync_total[5m])  # 同步操作频率
argocd_app_sync_total{phase="Failed"}  # 失败的同步

配置ArgoCD通知集成:

# argocd-notifications ConfigMap
apiVersion: v1
kind: ConfigMap
metadata:
  name: argocd-notifications-cm
  namespace: argocd
data:
  service.webhook.devops: |
    url: https://oapi.dingtalk.com/robot/send?access_token=xxx
    headers:
    - name: Content-Type
      value: application/json
  trigger.on-deployed: |
    - when: app.status.operationState.phase in ['Succeeded']
      send: [devops-notification]
  trigger.on-sync-failed: |
    - when: app.status.operationState.phase in ['Error', 'Failed']
      send: [devops-notification]
  template.devops-notification: |
    message: |
      ArgoCD同步{{.app.status.operationState.phase}}: {{.app.metadata.name}}
      集群: {{.app.spec.destination.server}}
      命名空间: {{.app.spec.destination.namespace}}
      仓库: {{.app.spec.source.repoURL}}

通过Git仓库管理ArgoCD Application配置,结合Kustomize多环境overlay和Image Updater自动镜像更新,构建从代码提交到集群部署的完整GitOps流水线。selfHeal机制确保集群状态始终与Git声明一致,任何手动kubectl操作都会被自动纠正,实现真正的声明式部署管理。

原创文章,作者:小编,如若转载,请注明出处:https://www.yunthe.com/argocdgitops-chi-xu-bu-shu-shi-zhan-kubernetes-ying-yong-zi/

(0)
小编小编
上一篇 1天前
下一篇 1天前

相关推荐