ArgoCD GitOps 持续部署平台部署与运维实战

一、背景介绍

1.1 什么是 GitOps

GitOps 是一种以 Git 作为”单一事实来源”的运维范式,通过声明式配置和自动化同步,实现基础设施和应用的可观测性、可追溯性和自动化部署。

1.2 为什么选择 ArgoCD

ArgoCD 是 CNCF 毕业项目,专为 Kubernetes 设计的 GitOps 持续交付工具,具有以下优势:

  • 声明式配置:所有资源状态由 Git 仓库定义
  • 自动化同步:自动检测并同步集群状态与 Git 配置
  • 可视化界面:直观的 Web UI 展示应用状态
  • 多集群支持:统一管理多个 Kubernetes 集群
  • 审计追踪:完整的变更历史和回滚能力

二、架构设计

2.1 核心组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
┌─────────────────────────────────────────────────────────────┐
│ ArgoCD 架构 │
├─────────────────────────────────────────────────────────────┤
│ ┌──────────────┐ │
│ │ Git Repo │ ← 声明式配置 (YAML/Helm/Kustomize) │
│ └──────┬───────┘ │
│ │ 推送/拉取 │
│ ▼ │
│ ┌──────────────┐ ┌──────────────┐ │
│ │ Repo Server │ │ Application │ │
│ │ (清单生成) │ │ Controller │ │
│ └──────────────┘ └──────┬───────┘ │
│ │ │
│ ▼ │
│ ┌──────────────┐ │
│ │ Kubernetes │ │
│ │ Cluster │ │
│ └──────────────┘ │
│ │ │
│ ┌────────────────────┼────────────────────┐ │
│ ▼ ▼ ▼ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Web UI/CLI │ │ API Server │ │ Notification │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────┘

2.2 工作流程

  1. 开发人员在 Git 仓库提交应用配置变更
  2. ArgoCD 检测到 Git 仓库变化
  3. Application Controller 比较期望状态与实际状态
  4. 自动或手动同步到 Kubernetes 集群
  5. 发送通知并记录审计日志

三、部署准备

3.1 环境要求

组件 版本要求
Kubernetes 1.23+
kubectl 与集群版本匹配
Helm 3.0+ (可选)
内存 至少 2GB
存储 支持 PersistentVolume

3.2 前置检查

1
2
3
4
5
6
7
8
9
10
11
# 检查 Kubernetes 集群
kubectl version --short

# 检查节点状态
kubectl get nodes

# 检查存储类
kubectl get storageclass

# 创建命名空间
kubectl create namespace argocd

四、部署 ArgoCD

4.1 方式一:使用官方 YAML(推荐新手)

1
2
3
4
5
6
7
8
# 下载并应用官方清单
kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml

# 等待所有组件就绪
kubectl wait --for=condition=Available deployment --all -n argocd --timeout=300s

# 验证部署
kubectl get all -n argocd

4.2 方式二:使用 Helm Chart(推荐生产)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# 添加 Argo Helm 仓库
helm repo add argo https://argoproj.github.io/argo-helm
helm repo update

# 创建 values.yaml 自定义配置
cat > argocd-values.yaml << 'EOF'
# 基础配置
global:
domain: argocd.example.com

# Server 配置
server:
ingress:
enabled: true
ingressClassName: nginx
annotations:
nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
nginx.ingress.kubernetes.io/ssl-passthrough: "true"
tls:
- hosts:
- argocd.example.com
secretName: argocd-tls

# Repo Server 配置
repoServer:
replicas: 2
resources:
requests:
cpu: 100m
memory: 256Mi
limits:
cpu: 500m
memory: 1Gi

# Application Controller 配置
controller:
replicas: 1
resources:
requests:
cpu: 250m
memory: 512Mi
limits:
cpu: 2
memory: 4Gi

# Redis 配置
redis:
enabled: true
resources:
requests:
cpu: 100m
memory: 128Mi

# 禁用内置的 Argo CD 通知
notifications:
enabled: false
EOF

# 安装 ArgoCD
helm install argocd argo/argo-cd -n argocd -f argocd-values.yaml

# 验证安装
helm test argocd -n argocd

4.3 方式三:使用 Kustomize

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 克隆 ArgoCD 仓库
git clone https://github.com/argoproj/argo-cd.git
cd argocd/manifests/cluster-install

# 应用清单
kubectl apply -k .

# 自定义配置(创建 kustomization.yaml)
cat > kustomization.yaml << 'EOF'
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- base
patches:
- path: argocd-cm-patch.yaml
EOF

五、初始配置

5.1 获取初始密码

1
2
3
4
5
6
# 获取 admin 初始密码
kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath="{.data.password}" | base64 -d

# 或使用 kubectl 命令
ARGOCD_PWD=$(kubectl -n argocd get secret argocd-initial-admin-secret -o jsonpath="{.data.password}" | base64 -d)
echo "Admin password: $ARGOCD_PWD"

5.2 登录 ArgoCD

1
2
3
4
5
6
7
8
9
10
11
# 方式一:Web UI
# 访问 https://argocd.example.com
# 用户名:admin
# 密码:上一步获取的密码

# 方式二:CLI
argocd login argocd.example.com --username admin --password $ARGOCD_PWD

# 方式三:端口转发(测试环境)
kubectl port-forward svc/argocd-server -n argocd 8080:443
argocd login localhost:8080 --username admin --password $ARGOCD_PWD --insecure

5.3 修改 admin 密码

1
2
3
4
5
6
7
# 使用 CLI 修改
argocd account update-password

# 或使用 Kubernetes 命令
ARGOCD_NEW_PWD="YourNewSecurePassword123!"
argocd bcrypt $ARGOCD_NEW_PWD | xargs -I {} kubectl -n argocd patch secret argocd-secret \
-p '{"stringData": {"admin.password": "{}","admin.passwordMtime": "'$(date +%FT%T%Z)'"}}'

六、连接 Git 仓库

6.1 添加 Git 仓库凭证

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 添加 HTTPS 仓库(使用 Personal Access Token)
argocd repo add https://github.com/your-org/your-repo.git \
--username your-username \
--password your-token \
--name production-repo

# 添加 SSH 仓库(推荐)
# 1. 生成 SSH 密钥
ssh-keygen -t ed25519 -f ~/.ssh/argocd-deploy-key -N ""

# 2. 将公钥添加到 Git 仓库 Deploy Keys
cat ~/.ssh/argocd-deploy-key.pub

# 3. 在 ArgoCD 中注册私钥
argocd repo add git@github.com:your-org/your-repo.git \
--ssh-private-key-path ~/.ssh/argocd-deploy-key \
--name production-repo

# 验证连接
argocd repo list
argocd repo get production-repo

6.2 使用 Kubernetes Secret 管理凭证

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# argocd-repo-secret.yaml
apiVersion: v1
kind: Secret
metadata:
name: my-repo-ssh-creds
namespace: argocd
labels:
argocd.argoproj.io/secret-type: repository
stringData:
type: git
url: git@github.com:your-org/your-repo.git
sshPrivateKey: |
-----BEGIN OPENSSH PRIVATE KEY-----
...
-----END OPENSSH PRIVATE KEY-----
1
kubectl apply -f argocd-repo-secret.yaml

七、创建 Application

7.1 方式一:CLI 创建

1
2
3
4
5
6
7
8
argocd app create guestbook \
--repo https://github.com/argoproj/argocd-example-apps.git \
--path guestbook \
--dest-server https://kubernetes.default.svc \
--dest-namespace default \
--sync-policy automated \
--auto-prune \
--self-heal

7.2 方式二:YAML 声明式创建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# guestbook-app.yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: guestbook
namespace: argocd
finalizers:
- resources-finalizer.argocd.argoproj.io
spec:
project: default
source:
repoURL: https://github.com/argoproj/argocd-example-apps.git
targetRevision: HEAD
path: guestbook
# Helm 配置示例
# helm:
# valueFiles:
# - values-production.yaml
# parameters:
# - name: image.tag
# value: v1.0.0
# Kustomize 配置示例
# kustomize:
# namePrefix: prod-
# commonLabels:
# environment: production
destination:
server: https://kubernetes.default.svc
namespace: default
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
1
kubectl apply -f guestbook-app.yaml

7.3 方式三:App of Apps 模式

适用于管理多个应用的场景:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# app-of-apps.yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: app-of-apps
namespace: argocd
spec:
project: default
source:
repoURL: https://github.com/your-org/gitops-repo.git
targetRevision: HEAD
path: environments/production
destination:
server: https://kubernetes.default.svc
namespace: argocd
syncPolicy:
automated:
prune: true
selfHeal: true

八、同步策略详解

8.1 同步选项

选项 说明
prune 自动删除 Git 中不存在但集群中存在的资源
selfHeal 当集群状态偏离时自动同步
allowEmpty 允许同步空清单(通常禁用)

8.2 高级同步选项

1
2
3
4
5
6
7
8
9
10
syncPolicy:
syncOptions:
- CreateNamespace=true # 自动创建命名空间
- Validate=true # 验证 YAML
- SkipDryRunOnMissingResource=true
- PrunePropagationPolicy=foreground # 删除传播策略
- PruneLast=true # 最后执行删除
- RespectIgnoreDifferences=true # 尊重忽略差异配置
- SyncOptions # 资源级同步选项
- ApplyOutOfSyncOnly=true # 仅同步不同步的资源

8.3 忽略差异配置

1
2
3
4
5
6
7
8
9
10
spec:
ignoreDifferences:
- group: apps
kind: Deployment
jsonPointers:
- /spec/replicas
- group: autoscaling
kind: HorizontalPodAutoscaler
jsonPointers:
- /spec/currentReplicas

九、多环境管理

9.1 Project 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# production-project.yaml
apiVersion: argoproj.io/v1alpha1
kind: AppProject
metadata:
name: production
namespace: argocd
spec:
description: Production projects
sourceRepos:
- https://github.com/your-org/your-repo.git
- git@github.com:your-org/your-repo.git
destinations:
- namespace: production-*
server: https://kubernetes.default.svc
- namespace: monitoring
server: https://kubernetes.default.svc
clusterResourceWhitelist:
- group: ''
kind: Namespace
- group: rbac.authorization.k8s.io
kind: ClusterRole
namespaceResourceBlacklist:
- group: ''
kind: ResourceQuota
- group: ''
kind: LimitRange
roles:
- name: admin
description: Admin access to production
policies:
- p, proj:production:admin, applications, *, production/*, allow
groups:
- production-admins

9.2 多集群配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# 添加远程集群
argocd cluster add <context-name> --name production-cluster

# 或使用 Secret
cat > cluster-secret.yaml << 'EOF'
apiVersion: v1
kind: Secret
metadata:
name: production-cluster
namespace: argocd
labels:
argocd.argoproj.io/secret-type: cluster
stringData:
name: production-cluster
server: https://prod-k8s-api.example.com:6443
config: |
{
"bearerToken": "<service-account-token>",
"tlsClientConfig": {
"insecure": false,
"caData": "<base64-encoded-ca-cert>"
}
}
EOF

kubectl apply -f cluster-secret.yaml

十、通知与告警

10.1 配置 Slack 通知

1
2
3
4
5
6
7
8
# argocd-notifications-secret.yaml
apiVersion: v1
kind: Secret
metadata:
name: argocd-notifications-secret
namespace: argocd
stringData:
slack-token: xoxb-your-slack-bot-token
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# argocd-notifications-cm.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: argocd-notifications-cm
namespace: argocd
data:
service.slack: |
token: $slack-token
template.app-sync-status: |
message: |
Application {{.app.metadata.name}} sync status is {{.app.status.sync.status}}
trigger.on-sync-status-changed: |
- when: app.status.sync.status == 'Synced'
send: [app-sync-status]
- when: app.status.sync.status == 'OutOfSync'
send: [app-sync-status]

10.2 配置 Webhook

1
2
3
4
5
6
# 在 Application 中添加注解
metadata:
annotations:
notifications.argoproj.io/subscribe.on-sync-succeeded.slack: my-channel
notifications.argoproj.io/subscribe.on-sync-failed.slack: my-channel
notifications.argoproj.io/subscribe.on-health-degraded.slack: my-channel

十一、运维管理

11.1 备份与恢复

1
2
3
4
5
6
7
8
9
# 备份 ArgoCD 配置
kubectl get applications -n argocd -o yaml > applications-backup.yaml
kubectl get appprojects -n argocd -o yaml > appprojects-backup.yaml
kubectl get secrets -n argocd -l argocd.argoproj.io/secret-type=repository -o yaml > repo-secrets-backup.yaml
kubectl get secrets -n argocd -l argocd.argoproj.io/secret-type=cluster -o yaml > cluster-secrets-backup.yaml

# 恢复配置
kubectl apply -f applications-backup.yaml
kubectl apply -f appprojects-backup.yaml

11.2 升级 ArgoCD

1
2
3
4
5
# Helm 升级
helm upgrade argocd argo/argo-cd -n argocd -f argocd-values.yaml

# YAML 方式升级
kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml

11.3 性能调优

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Application Controller 调优
controller:
resources:
requests:
cpu: 500m
memory: 1Gi
limits:
cpu: 4
memory: 8Gi
env:
- name: ARGOCD_APPLICATION_CONTROLLER_STATUS_PROCESSORS
value: "20"
- name: ARGOCD_APPLICATION_CONTROLLER_OPERATION_PROCESSORS
value: "10"

# Repo Server 调优
repoServer:
replicas: 3
resources:
requests:
cpu: 250m
memory: 512Mi
limits:
cpu: 2
memory: 4Gi

11.4 监控指标

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 启用 metrics
kubectl -n argocd get svc argocd-metrics
kubectl -n argocd get svc argocd-repo-server-metrics
kubectl -n argocd get svc argocd-server-metrics

# Prometheus 抓取配置
scrape_configs:
- job_name: 'argocd'
kubernetes_sd_configs:
- role: endpoints
relabel_configs:
- source_labels: [__meta_kubernetes_namespace]
regex: argocd
action: keep
- source_labels: [__meta_kubernetes_service_label_app_kubernetes_io_name]
regex: argocd-server
action: keep

十二、故障排查

12.1 常见问题

问题 1:应用一直处于 OutOfSync 状态

1
2
3
4
5
6
7
8
# 查看差异
argocd app diff guestbook

# 强制同步
argocd app sync guestbook --force

# 查看事件
kubectl get events -n default --sort-by='.lastTimestamp'

问题 2:Git 仓库连接失败

1
2
3
4
5
6
7
8
# 测试连接
argocd repo get <repo-name>

# 查看 Repo Server 日志
kubectl logs -n argocd -l app.kubernetes.io/name=argocd-repo-server

# 检查 SSH 密钥
kubectl -n argocd get secret <repo-secret> -o jsonpath='{.data.sshPrivateKey}' | base64 -d

问题 3:同步超时

1
2
3
4
# 增加超时时间
kubectl -n argocd edit deployment argocd-application-controller
# 添加环境变量:
# ARGOCD_APPLICATION_SYNC_TIMEOUT=300s

12.2 日志收集

1
2
3
4
5
# 收集所有组件日志
kubectl logs -n argocd -l app.kubernetes.io/part-of=argocd --tail=1000 > argocd-logs.txt

# 实时查看
kubectl logs -n argocd -l app.kubernetes.io/name=argocd-application-controller -f

十三、最佳实践

13.1 Git 仓库结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
gitops-repo/
├── applications/ # Application 定义
│ ├── guestbook.yaml
│ └── monitoring.yaml
├── base/ # 基础配置
│ ├── deployments/
│ ├── services/
│ └── configmaps/
├── overlays/ # 环境覆盖
│ ├── development/
│ ├── staging/
│ └── production/
├── projects/ # AppProject 定义
└── clusters/ # 集群配置

13.2 安全建议

  1. 使用 SSH 而非 HTTPS:更安全,无需存储密码
  2. 最小权限原则:为不同环境创建独立 Project
  3. 启用 SSO:集成 OIDC/LDAP
  4. 审计日志:定期审查变更历史
  5. Secret 管理:使用 External Secrets 或 Sealed Secrets

13.3 CI/CD 集成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# GitHub Actions 示例
name: Update GitOps
on:
push:
branches: [main]
jobs:
update-gitops:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Update image tag
run: |
sed -i "s|image:.*|image: myapp:${{ github.sha }}|" overlays/production/deployment.yaml
- name: Commit changes
run: |
git config user.name "GitHub Actions"
git config user.email "actions@github.com"
git commit -am "Update image to ${{ github.sha }}"
git push

十四、总结

ArgoCD 作为 GitOps 实践的核心工具,能够显著提升 Kubernetes 应用部署的可靠性和可追溯性。关键要点:

  1. 声明式配置:所有状态由 Git 定义
  2. 自动化同步:减少人为错误
  3. 可视化监控:实时了解应用状态
  4. 审计追踪:完整变更记录
  5. 多环境管理:统一管控多个集群

通过合理配置和最佳实践,ArgoCD 可以成为 Kubernetes 运维的得力助手。


文档版本: v1.0
最后更新: 2026-03-18
参考文档: