ArgoCD
安装
# 安装 ArgoCD
kubectl create namespace argocd
kubectl apply -n argocd -f \
https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml
# 获取初始密码
argocd admin initial-password -n argocd
# CLI 登录
argocd login localhost:8080
Application 资源
app.yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: my-app
namespace: argocd
spec:
project: default
source:
repoURL: https://github.com/org/k8s-manifests.git
targetRevision: main
path: apps/my-app/overlays/production
destination:
server: https://kubernetes.default.svc
namespace: production
syncPolicy:
automated:
prune: true # 删除 Git 中不存在的资源
selfHeal: true # 自动修复漂移
syncOptions:
- CreateNamespace=true
retry:
limit: 5
backoff:
duration: 5s
factor: 2
maxDuration: 3m
Sync 策略
| 策略 | 说明 | 适用场景 |
|---|---|---|
| 手动 Sync | 需要点击按钮或执行命令 | 生产环境谨慎部署 |
| 自动 Sync | Git 变更后自动同步 | 开发/预发环境 |
selfHeal | 检测到集群漂移自动修复 | 防止手动修改 |
prune | 删除 Git 中不存在的资源 | 保持 Git 与集群一致 |
ApplicationSet(多集群/多环境)
appset.yaml
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
name: my-app
namespace: argocd
spec:
generators:
- list:
elements:
- cluster: dev
url: https://dev-cluster.example.com
- cluster: staging
url: https://staging-cluster.example.com
- cluster: production
url: https://prod-cluster.example.com
template:
metadata:
name: "my-app-{{cluster}}"
spec:
project: default
source:
repoURL: https://github.com/org/k8s-manifests.git
targetRevision: main
path: "apps/my-app/overlays/{{cluster}}"
destination:
server: "{{url}}"
namespace: my-app
RBAC 配置
argocd-rbac-cm (ConfigMap)
# 角色定义
p, role:developer, applications, get, */*, allow
p, role:developer, applications, sync, */dev-*, allow
p, role:ops, applications, *, */*, allow
# 用户绑定
g, dev-team, role:developer
g, ops-team, role:ops
常见面试问题
Q1: ArgoCD 如何实现回滚?
答案:
ArgoCD 有两种回滚方式:
- Git Revert(推荐):
git revert提交回滚 commit,ArgoCD 自动同步,符合 GitOps 原则 - ArgoCD 回滚:
argocd app rollback my-app回退到历史版本,但这会导致 Git 与集群状态不一致
最佳实践是始终通过 Git 操作来回滚,保持 Git 作为唯一真实来源。