Skip to content

GitOps: اصول، Argo CD، Flux، Drift و Image Automation ​

"Software agents continuously observe actual system state and attempt to apply the desired state." — OpenGitOps, GitOps Principles v1.0.0, principle 4 "Continuously Reconciled"

خلاصه (Summary): در GitOps خوشه (Cluster) وضعیت مطلوب (Desired state) را از محل نگهداری نسخه‌دار، معمولاً Repository پیکربندی (Config repository)، دریافت می‌کند. عامل (Agent) داخل Cluster وضعیت زنده (Live state) را با آن یکسان نگه می‌دارد: یکپارچه‌سازی پیوسته (CI) به‌جای استقرار (Deployment)، ثبت تغییر (Commit) پیشنهاد می‌کند؛ هر تغییر تفاوت بازبینی‌شده (Diff) است؛ انحراف (Drift) شناسایی و برگردانده می‌شود و بازگشت (Rollback) با git revert انجام می‌شود. Argo CD و Flux دو Agent فارغ‌التحصیل CNCF برای این کار در Kubernetes هستند. تمرکز (Focus): چهار اصل OpenGitOps: بیان اعلانی (Declarative)، نسخه‌داری و تغییرناپذیری (Versioned and immutable)، دریافت خودکار (Pulled automatically) و آشتی‌دهی پیوسته (Continuously reconciled)؛ استقرار فشاری و کششی (Push/Pull deployment)، حلقهٔ آشتی‌دهی (Reconciliation loop) و Drift؛ چیدمان Config repository و Repository برنامه (App repository)، Monorepo و repo هر محیط، پوشه‌های محیط با لایه‌های پوششی Kustomize (Overlays) یا مقادیر Helm (Values) و ضدالگوی شاخهٔ جدا برای هر محیط؛ معماری Argo CD شامل api-server، repo-server، application-controller و Redis، تعریف منبع سفارشی (CRD) برای Application و AppProject، سیاست همگام‌سازی (Sync policy)، همگام‌سازی خودکار (Automated sync)، هرس (Prune)، خود‌ترمیمی (Self-heal)، گزینه‌ها، موج‌های همگام‌سازی (Sync waves) و قلاب‌های همگام‌سازی (Sync hooks) با PreSync/PostSync، سلامت (Health) در Healthy، Progressing و Degraded، OutOfSync و ignoreDifferences؛ ApplicationSet با مولدهای (Generators) Git، Cluster، Matrix و Pull Request، app of apps، کنترل دسترسی مبتنی بر نقش (RBAC)، ورود یکپارچه (SSO)، Argo CD Notifications و Argo CD Image Updater؛ کنترل‌گرهای (Controllers) Flux شامل source-controller، kustomize-controller، helm-controller، notification-controller، image-reflector-controller و image-automation-controller، GitRepository و OCIRepository، Kustomization با dependsOn و بررسی سلامت (Health checks)، HelmRelease با تشخیص Drift، Receiver و Alert و Provider، ImageRepository و ImagePolicy و ImageUpdateAutomation برای نوشتن نتیجه در Git، flux bootstrap و چندمستاجری (Multi-tenancy)؛ اسرار (Secrets)، ارتقای محیط (Environment promotion) با درخواست ادغام (Pull request) تغییر برچسب تصویر (Image tag) و Kargo، Revert در برابر argocd app rollback، تحویل تدریجی (Progressive delivery)، مصنوع‌های OCI (OCI artifacts)، زیرساخت با Crossplane و Tofu Controller، سنجه‌های Sync در Prometheus و ضدالگوها (Anti-patterns). هدف یادگیری (Learning goal): برای سرویس Go و برنامهٔ Laravel یک Config repository با Overlay هر محیط بسازید؛ آن‌ها را با Argo CD و Application، AppProject و ApplicationSet یا با Flux و Kustomization، HelmRelease و خودکارسازی تصویر (Image automation) برای Tag برنامهٔ Laravel تحویل دهید. مهاجرت پایگاه داده (Migration) و تست سلامت اولیه (Smoke test) را با Hook مرتب کنید؛ با PR از پیش‌تولید (Staging) به محیط عملیاتی (Production) ارتقا دهید؛ دربارهٔ روشن یا خاموش‌بودن Self-heal تصمیم بگیرید و Sync گیرکرده، OutOfSync یا Degraded را عیب‌یابی کنید.

این فصل بخش تحویل از گروه Delivery & Infrastructure است. رندر (Render) توصیف استقرار (Manifest) با Kustomize و Helm در بسته‌بندی برای Kubernetes آمده؛ اینجا از Overlay استفاده می‌کنیم و دوباره آن را آموزش نمی‌دهیم. خط لوله (Pipeline) ساخت، تست، اسکن و امضای تصویر (Image) و اعتماد OIDC میان CI و مخزن تصویر (Registry) در Pipelineهای CI/CD است. Canary، Blue-green و Rollback ترافیک در راهبردهای استقرار، Sealed Secrets و SOPS و External Secrets Operator در پیکربندی، Secrets و Storage، محدودیت RBAC عامل در امنیت Kubernetes، Deployment و کاوشگر سلامت (Probe) و استقرار تدریجی (Rollout) در بارهای کاری Kubernetes بررسی شده‌اند. خود Imageها در Image و Dockerfile، وضعیت Terraform و Plan/Apply در زیرساخت به‌شکل کد و شاخه‌بندی و PR در Git و کنترل نسخه هستند. برای چرایی استفادهٔ سازمان از Kubernetes به کانتینر و Kubernetes و برای ممیزی، مدیریت تغییر و رخداد به SDLC امن و پاسخ به رخداد رجوع کنید.

نسخه‌های بررسی‌شده در ۲۹ نوامبر ۲۰۲۶: Argo CD v3.6.3، آخرین انتشار در ۲۴ نوامبر؛ Flux v2.10.1، انتشار ۲۰ نوامبر؛ Argo CD Image Updater v1.x مبتنی بر CRD؛ OpenGitOps Principles v1.0.0. در محیط ساخت این فصل Cluster وجود ندارد؛ تمام فرمان‌های argocd، flux و kubectl apply این صفحه خروجی مورد انتظار دارند و اجرا نشده‌اند. Overlayها روی میزبان رندر شده‌اند و ابزارهای Go واقعاً اجرا شده‌اند؛ آزمایشگاه را ببینید.

نقشهٔ صفحه (Page map) ​

اگر دنبال این موضوع هستیدبه این بخش بروید
کل صفحه در سه جدولهمه‌چیز در یک دقیقه
دلیل برتری Pull بر Push برای استقرارچرا وجود دارد
تاریخ Flux در 2016، Argo در 2017، OpenGitOps 1.0 و فارغ‌التحصیلی CNCFاز کجا آمده
اعلانی‌بودن، نسخه‌داری و تغییرناپذیری، دریافت خودکار و Reconciliation پیوستهاصول OpenGitOps
مقایسهٔ استقرار Push و PullPush و Pull
وضعیت مطلوب، حلقهٔ Reconciliation و Driftحلقهٔ Reconciliation
تفاوت Config repository و App repository، Monorepo، پوشهٔ هر محیط، ضدالگوی شاخهٔ محیط و استفاده از Overlayهای Kustomize یا Values هر محیط در Helmچیدمان Repository
نقش api-server، repo-server، application-controller و Redisمعماری Argo CD
کاربرد Application CRD و AppProjectApplication و Project
سیاست Sync، Automated sync، Prune، selfHeal و گزینه‌های Syncسیاست Sync
ترتیب اجرا با Sync waves و Sync hooks، از PreSync تا PostSyncموج‌ها و Hookها
معنای Health در Degraded، Progressing و Healthy و تفاوتش با OutOfSyncوضعیت Health و Sync
مقایسهٔ تغییرها و ignoreDifferencesمحاسبهٔ Diff
ApplicationSet با مولدهای Git، Cluster، Matrix و Pull Request و app of appsApplicationSet و app of apps
دسترسی و اعلان در Argo CD با RBAC، SSO و NotificationsRBAC، SSO و اعلان‌ها
به‌روزرسانی تصویر با Argo CD Image UpdaterImage Updater
وظایف source-controller، kustomize-controller، helm-controller، notification-controller و کنترل‌گرهای تصویرکنترل‌گرهای Flux
دریافت GitRepository، OCIRepository و OCI artifactsمنابع Flux
Kustomization، dependsOn و Health checksKustomization در Flux
انتشار Helm با HelmReleaseHelmRelease
ورود و خروج رویداد با Receiver، Alert و Providerاعلان‌های Flux
ImageRepository، ImagePolicy و ImageUpdateAutomation و نوشتن نتیجه در GitImage automation
آماده‌سازی با flux bootstrap و Multi-tenancyBootstrap و Multi-tenancy
تشخیص Drift، Self-heal و برگرداندن تغییر دستیDrift و Self-heal
مدیریت Secrets با SOPS، Sealed Secrets و ESOSecrets
Promotion محیط، PR تغییر Image tag و KargoPromotion
مقایسهٔ Revert با argocd app rollbackRollback
نقش Argo Rollouts و Flaggerتحویل تدریجی
آشنایی با Crossplane و tf-controllerGitOps برای زیرساخت
سنجه‌های Sync در Prometheusمشاهده‌پذیری
ضدالگوهای kubectl apply از CI، دسترسی cluster-admin در CI و شاخه‌های بلندعمرضدالگوها
Reconciliation گام‌به‌گام، تنظیمات و دلیل وضعیت‌هاسازوکار
قطعه‌کدهاGo، Laravel
مسئله‌های کلاسیک و راه‌حل‌هاحل مسئله‌های کلاسیک
انتخاب Argo CD یا Flux، چیدمان و Image automationانتخاب
حرکت از یک Cluster به مجموعه‌ای از Clusterهادر معماری
فرمان‌ها با خروجی واقعی و مورد انتظارآزمایشگاه
باورهای نادرست، چکیده، پرسش‌ها و اصطلاحاتبدفهمی‌ها، چکیده، خودآزمایی، واژه‌نامه

همه‌چیز در یک دقیقه (Everything in one minute) ​

چهار اصل OpenGitOps، نسخهٔ v1.0.0، ۸ اکتبر ۲۰۲۱.

اصلعبارت دقیقبه زبان سادهچه چیزی آن را نقض می‌کند
اعلانی (Declarative)"A system managed by GitOps must have its desired state expressed declaratively."فایل‌ها نتیجهٔ نهایی را توصیف می‌کنند، نه مراحلاسکریپت استقرار، kubectl set image در Pipeline
نسخه‌دار و تغییرناپذیر (Versioned and Immutable)"Desired state is stored in a way that enforces immutability, versioning and retains a complete version history."هر تغییر یک Commit است؛ تاریخچه بازنویسی نمی‌شودForce-push به main، Tag تغییرپذیر latest و پایهٔ دوردست (Remote base) روی HEAD
دریافت خودکار (Pulled Automatically)"Software agents automatically pull the desired state declarations from the source."Cluster خودش دریافت می‌کند؛ کسی به داخلش Push نمی‌کندنگهداری kubeconfig در CI و اجرای kubectl apply
آشتی‌دهی پیوسته (Continuously Reconciled)"Software agents continuously observe actual system state and attempt to apply the desired state."همیشگی است، حتی پس از Drift؛ محدود به اجرای Pipeline نیستSelf-heal خاموش باشد و کسی OutOfSync را پایش نکند

مقایسهٔ Argo CD و Flux در یک جدول.

موضوعArgo CDFlux
واحد تحویل (Unit of delivery)Application شامل منبع، مقصد و Sync policyKustomization یا HelmRelease که به شیء منبع اشاره دارد
گروه‌بندی و محافظ‌ها (Guardrails)AppProject: repoهای منبع، مقصدها، Kindهای مجاز و نقش‌هافضاهای نام (Namespaces) در Kubernetes و RBAC؛ عمل‌کردن با هویت serviceAccountName
گسترش به چند مقصد (Fan-out)مولدهای ApplicationSet؛ app of appsKustomizationهایی که Kustomization می‌سازند؛ یکی برای هر پوشهٔ Cluster
سرکشی پیش‌فرض (Poll)120 s به‌علاوهٔ حداکثر 60 s نوسان زمانی (Jitter) (timeout.reconciliation).spec.interval هر شیء؛ مستندات مفاهیم دربارهٔ Kustomization می‌گویند "every five minutes by default"؛ مقدار را شما تعیین می‌کنید
اصلاح DriftselfHeal: true؛ پیش‌فرض خاموشبرای Kustomization در هر بازه فعال؛ برای HelmRelease با driftDetection.mode
ترتیب اجراSync waves و Hookها: PreSync، Sync، PostSync، SyncFail، PreDelete و PostDeletedependsOn میان Kustomizationها/HelmReleaseها؛ wait / healthChecks
Helmرندر با helm template؛ در helm list نیستانتشار واقعی Helm با helm-controller؛ در helm list هست
رابط کاربری (UI) و کاربرانWeb UI، SSO با Dex یا OIDC، RBAC با CasbinUI داخلی ندارد؛ Kubernetes RBAC و CLI با flux
خودکارسازی تصویر (Image automation)Argo CD Image Updater، پروژهٔ جدا با ImageUpdater CRimage-reflector-controller و image-automation-controller با --components-extra
اعلان‌ها (Notifications)Argo CD Notifications با argocd-notifications-cm و Triggerهاnotification-controller: Alert، Provider و Receiver
ارتقا (Promotion)داخلی نیست؛ Kargo، ربات PR یا نوشتن نتیجهٔ Image Updaterداخلی نیست؛ Image automation به شاخهٔ PR، Kargo یا CI

وضعیت‌هایی که هر روز می‌بینید.

وضعیتابزارمعنیاولین بررسی
SyncedArgo CDوضعیت زنده با رندر Git یکسان استکاری لازم نیست؛ Health را هم ببینید
OutOfSyncArgo CDحداقل یک شیء متفاوت است یا وجود نداردargocd app diff؛ مورد انتظار، اجرا نشده
Healthy / Suspended / Progressing / Missing / Degraded / UnknownArgo CDسلامت بار کاری (Workload) مستقل از Sync؛ بدترین فرزند وضعیت برنامه را تعیین می‌کند؛ ترتیب از سالم‌ترین به ناسالم‌ترین استRollout، Probeها و رویدادها
Ready=TrueFluxآخرین Reconciliation اعمال شده و با wait سلامت هم بررسی شدهflux get kustomizations
Ready=False با دلیل BuildFailed، HealthCheckFailed، DependencyNotReadyFluxخطای ساخت، Workload ناسالم یا آماده‌نبودن dependsOnflux events، flux tree
OutOfSync همراه منبع علامت‌خورده برای PruneArgo CDمنبع متعلق به برنامه بوده، از Git حذف شده و Prune خاموش است: "The app will be out of sync if Argo CD expects a resource to be pruned"Prune را فعال کنید یا یک Sync با انتخاب Prune انجام دهید
Push: CI deploysgit pushCI runnerholds cluster-admin kubeconfigCluster API (must be reachable)applied once; drift never seenkubectl applyPull: an agent in the cluster reconcilesCI: build, pushimage + commit / PRConfig repo (Git)desired state, versionedcluster (no inbound access needed)Agent: Argo CD / FluxLive objects1 pull3 apply diff2 observe, compareLoop repeats on an interval, on a webhook,and whenever live state drifts:kubectl edit is reverted (self-heal),objects removed from Git are pruned.

چرا وجود دارد (Why it exists) ​

اولین Pipeline معمولاً استقرار فشاری (Push deployment) دارد: کار (Job) در CI یک kubeconfig نگه می‌دارد، kubectl apply یا helm upgrade اجرا می‌کند و سبز می‌شود. روز اول جواب می‌دهد. روز نودم برای فهمیدن وضعیت Production باید از Cluster بپرسید؛ چون ساعت دو بامداد اصلاح اضطراری با kubectl edit انجام شده است. CI اعتبارنامه‌ای (Credentials) دارد که تمام Namespaceها را حذف می‌کند؛ API خوشه باید از شبکهٔ ارائه‌دهندهٔ CI در دسترس باشد؛ حذف Manifest، Deployment را در حال اجرا باقی می‌گذارد؛ و Rollback یعنی اجرای Pipeline قدیمی با امید اینکه هنوز ساخته شود.

GitOps جهت را برمی‌گرداند. تنها مسیر نوشتن در Cluster، Agent داخل آن است که Pull می‌کند. انسان و CI، Repository را تغییر می‌دهند؛ Agent وضعیت Cluster را با Repository یکسان می‌کند و یکسان نگه می‌دارد. Repository هم‌زمان سابقهٔ ممیزی، دروازهٔ بازبینی، سازوکار Rollback و برنامهٔ بازیابی پیکربندی Cluster پس از بحران می‌شود.

انتخاب ساده‌ترانتخاب کامل‌تردستاوردهزینه
CI، kubectl apply اجرا می‌کندAgent داخل Cluster دریافت می‌کندحذف اعتبارنامهٔ Cluster از CI و دسترسی ورودی API؛ Drift آشکاربهره‌برداری و ارتقای سیستم دیگر: Argo CD یا Flux
Apply در هر اجرای Pipelineآشتی‌دهی پیوسته (Continuous reconciliation)برگرداندن تغییر دستی و Prune اشیای حذف‌شدهkubectl edit اضطراری برمی‌گردد مگر ابتدا Suspend کنید
Manifest کنار کدConfig repository جداممیزی تمیز، دسترسی جدا، حذف حلقهٔ CIrepo دوم و مرحلهٔ Promotion
یک شاخه برای هر محیطپوشهٔ هر محیط روی mainتفاوت محیط‌ها روشن است؛ Drift ناشی از Merge نداریدنظم در Overlayها
Tag تغییرپذیرTag همراه چکیدهٔ محتوا (Digest) در GitCommit بایت‌های دقیق را مشخص می‌کند؛ Rollback دقیق استابزار نوشتن Digest
تغییر دستی TagImage automation یا ربات PromotionStaging سریع؛ Production پشت تأیید PRاعتبارنامهٔ ربات با حق نوشتن در Git

تشبیه این صفحه: ترموستات همراه دفتر ثبت. دفتر، همان Config repository، می‌گوید «دمای تمام اتاق‌ها ۲۱ درجه باشد». فقط نوشته‌های امضاشده و تاریخ‌دار پذیرفته می‌شوند و نوشتهٔ قدیمی پاک نمی‌شود. ترموستات، همان Agent، دفتر را می‌خواند، دمای اتاق یعنی Live state را اندازه می‌گیرد و بخاری را تا رسیدن به دمای خواسته‌شده تنظیم می‌کند. بازکردن پنجره مانند kubectl edit است: Agent، Drift را می‌بیند و اصلاح می‌کند. برای تغییر دما باید ورودی تازه در دفتر بنویسید؛ دست‌کاری رادیاتور کافی نیست. Rollback یعنی دوباره نوشتن مقدار دیروز. متخصص گرمایش، یعنی CI، رادیاتورها را تغییر نمی‌دهد؛ بخاری بهتر یا Image تازه می‌سازد و ورودی دفتر را پیشنهاد می‌کند.

سه بدفهمی رایج، از همین ابتدا ​

۱. «GitOps یعنی نگهداری YAML در Git.» همهٔ تیم‌ها این کار را می‌کنند. تفاوت در اصل سوم و چهارم است: Agent خودش Pull می‌کند و Reconciliation را ادامه می‌دهد. Repository که CI آن را Apply می‌کند، Push متکی به Git است، نه GitOps. Push و Pull را ببینید. ۲. «Argo CD به‌صورت پیش‌فرض تغییر دستی را برمی‌گرداند.» چنین نیست: "By default, changes that are made to the live cluster will not trigger automated sync"؛ باید selfHeal: true باشد. خود Automated sync هم نیاز به فعال‌سازی دارد. kustomize-controller در Flux در هر بازه دوباره Apply می‌کند. Drift و Self-heal را ببینید. ۳. «Rollback همان کلیک History → Rollback است.» در Argo CD، "Rollback cannot be performed against an application with automated sync enabled". حتی وقتی مجاز باشد، Git و Cluster را متفاوت باقی می‌گذارد. Rollback در GitOps با git revert است؛ Rollback.

از کجا آمده (Where it comes from) ​

زمانرویدادمنبع
2016Flux: "was initially developed by Weaveworks and made open source in 2016"بخش History در README مربوط به Flux v1
2017Argo: "Created and open sourced in 2017 by Applatix, which was acquired by Intuit"اعلام فارغ‌التحصیلی Argo در CNCF
2019"in 2019 Weaveworks decided to donate the project to CNCF" دربارهٔ FluxREADME مربوط به Flux v1
آوریل 2020Argo: "accepted into the CNCF Incubator in April 2020"اعلام CNCF
8 اکتبر 2021OpenGitOps Documents v1.0.0: "the first full release of the Principles and Glossary by the GitOps Working Group"انتشارهای open-gitops/documents
Argo CD v2.3"Starting with Argo CD v2.3, the ApplicationSet controller is bundled with Argo CD"مستندات ApplicationSet
30 نوامبر 2022فارغ‌التحصیلی Flux: "It is the 18th CNCF project to graduate"اعلام CNCF
6 دسامبر 2022فارغ‌التحصیلی Argo شامل Workflows، Events، Argo CD و Argo Rolloutsاعلام CNCF
Flux v2Flux v1: "has reached end of life and has been replaced by fluxcd/flux2 and its controllers entirely"README مربوط به Flux v1
Image Updater v1.0.0"a major transition from an annotation-based configuration to a CRD-based configuration" با ImageUpdater CRمستندات Argo CD Image Updater
Argo CD 3.xرهگیری با Annotation یعنی argocd.argoproj.io/tracking-id روش پیش‌فرض استمستندات Resource tracking
نوامبر 2026Argo CD v3.6.3 در 24 نوامبر، Flux v2.10.1 در 20 نوامبرانتشارهای GitHub

واژهٔ GitOps را معمولاً به نوشتهٔ Weaveworks در سال ۲۰۱۷ نسبت می‌دهند. دامنهٔ آن نوشته دیگر متن را ارائه نمی‌کند؛ بنابراین اینجا از آن نقل‌قول نمی‌کنیم و تعریف‌ها را از OpenGitOps می‌گیریم. ریشهٔ متفاوت دو ابزار، طراحی آن‌ها را توضیح می‌دهد. Flux ابتدا یک عملگر (Operator) برای Sync کردن Repository بود و بعد به GitOps Toolkit تقسیم شد: کنترل‌گرهای کوچک (Controllers)، هرکدام با خانوادهٔ CRD خود، بدون UI و با Kubernetes RBAC برای همه‌چیز. Argo CD از ابتدا محصول تحویل برنامه با UI، کاربران و RBAC اختصاصی و Controller مرکزی برای چند Cluster بود. هر دو اکنون علاوه بر Git از OCI artifacts به‌عنوان منبع پشتیبانی می‌کنند.

فهرست مفاهیم (The concept catalogue) ​

هر مفهوم با همین ترتیب توضیح داده می‌شود: بیان ساده، بدفهمی رایج، تعریف دقیق، توالی رخدادها، سناریوهای واقعی، رفتار هر محصول و راه‌حل.

اصول OpenGitOps: اعلانی، نسخه‌دار و تغییرناپذیر، دریافت خودکار و آشتی‌دهی پیوسته حیاتی ​

به زبان ساده: خواسته‌تان را بنویسید، تمام نسخه‌های آن را نگه دارید، بگذارید برنامه‌ای در سیستم مقصد آن را دریافت کند و تا یکسان‌شدن وضعیت واقعی با خواسته، اصلاح را ادامه دهد.

بدفهمی رایج: «Git اجباری است.» واژه‌نامه، محل نگهداری وضعیت (State store) را چنین تعریف می‌کند: "A system for storing immutable versions of desired state declarations" و می‌افزاید: "Git, from which GitOps derives its name, is the canonical example used as this state store but any other system that meets these criteria may be used." مخزن تصویر (Registry) سازگار با OCI که Config artifact امضاشده و تغییرناپذیر نگه دارد هم واجد شرایط است؛ Flux آن را "Gitless GitOps" می‌نامد.

تعریف: طبق OpenGitOps، وضعیت مطلوب (Desired state) باید اعلانی، نسخه‌دار و تغییرناپذیر باشد، خودکار دریافت شود و پیوسته آشتی‌دهی شود. تعریف Desired state عبارت است از "The aggregate of all configuration data that is sufficient to recreate the system so that instances of the system are behaviourally indistinguishable"؛ صریحاً "persistent application data, eg. database contents" را شامل نمی‌شود. منظور از پیوستگی (Continuous) نیز این است: "is intended to match the industry standard term: reconciliation continues to happen, not that it must be instantaneous."

text
Day in the life of one change under the four principles
1  developer opens a PR: apps/orders-api/overlays/prod newTag 1.4.2 -> 1.5.0   (declarative)
2  review + merge: commit c4f1e9a on main, signed, never rewritten               (versioned and immutable)
3  agent in the prod cluster fetches main at its next poll or on a webhook       (pulled automatically)
4  agent diffs, applies, then keeps comparing every few minutes                  (continuously reconciled)
5  someone runs kubectl scale --replicas=0 at 02:00 -> next comparison reverts it (drift corrected)

سناریوهای واقعی:

  • ممیز می‌پرسد چه کسی محدودیت منابع سرویس پرداخت را در مارس تغییر داد: git log -p apps/payments/ نام‌ها، بازبین‌ها و زمان‌ها را نشان می‌دهد.
  • Cluster از دست رفته است: Cluster تازه با Bootstrap از همان Repository به همان Desired state می‌رسد؛ دادهٔ ماندگار از پشتیبان بازمی‌گردد، نه Git.
  • تیمی با اجرای kubectl apply -k از GitHub Actions ادعای GitOps دارد؛ اصل سوم و چهارم نقض شده و Drift نامرئی است.
  • اگر Config repo از Base دوردست Kustomize روی HEAD استفاده کند، تغییرناپذیری نقض می‌شود: همان Commit هفتهٔ بعد خروجی دیگری می‌سازد.
محصولچگونگی اجرای چهار اصل
Argo CDApplication CR اعلانی؛ منبع Git/Helm/OCI در Revision مشخص؛ Pull و مقایسه با application-controller؛ Self-heal اختیاری
Fluxاشیای منبع از Git/OCI/Helm/Bucket دریافت می‌کنند؛ Kustomization/HelmRelease با .spec.interval آشتی‌دهی می‌شوند؛ اصلاح Drift برای Kustomization پیش‌فرض است
Kargoروی Agent مانند Argo CD بنا می‌شود؛ Promotion وضعیت مطلوب میان Stageها را اضافه می‌کند، نه Reconciliation
CI ساده و kubectl applyاعلانی و نسخه‌دار است، اما Push و یک‌بار Apply می‌شود؛ GitOps نیست

راه‌حل / روش استفاده: چهار اصل را برای هر مسیر ورود تغییر به Cluster بررسی کنید. اگر CI، فرد دارای cluster-admin یا UI یک Operator بدون عبور از State store در Cluster می‌نویسد، آن مسیر را حذف کنید یا اثرش را به‌شکل Drift آشکار کنید.

استقرار فشاری و کششی (Push vs pull deployment) حیاتی ​

به زبان ساده: در Push، Pipeline به Cluster دسترسی می‌گیرد؛ در Pull، Cluster به Repository مراجعه می‌کند.

بدفهمی رایج: «Pull فقط جزئیات امنیتی است.» این انتخاب تعیین می‌کند چه کسی Drift را می‌بیند. Pipeline فشاری فقط هنگام اجرا عمل می‌کند. تعریف Pull در واژه‌نامه می‌گوید Agentها "must be able to access the desired state from the state store at any time, not only when there is an intentional change in the state store triggering a push event" و این "is a prerequisite for reconciliation to happen continuously" است.

تعریف: در استقرار فشاری (Push deployment)، سیستم بیرونی مانند CI یا ابزار Deploy اعتبارنامهٔ Cluster دارد و هنگام اجرای Pipeline تغییرها را Apply می‌کند. در استقرار کششی (Pull deployment)، Agent داخل مقصد وضعیت مطلوب را دریافت و خودش اعمال می‌کند؛ سیستم بیرونی فقط در State store می‌نویسد. مستندات Auto-sync در Argo CD نتیجه را روشن می‌کنند: "CI/CD pipelines no longer need direct access to the Argo CD API server to perform the deployment. Instead, the pipeline makes a commit and push to the Git repository".

text
push                                         pull
1 CI: build + push image                     1 CI: build + push image
2 CI: kubectl apply (cluster-admin token)    2 CI (or bot): commit new tag to config repo
3 done; nothing watches the cluster          3 agent: poll/webhook -> fetch -> diff -> apply
                                             4 agent: repeat forever; report Synced/Healthy

سناریوهای واقعی:

  • Cluster خصوصی EKS/GKE بدون API عمومی: CI فشاری به VPN یا Runner خودمیزبان داخل VPC نیاز دارد؛ Agent کششی فقط خروجی شبکه به Git و Registry لازم دارد.
  • افشای Secret در CI فشاری یعنی تصاحب Cluster؛ در Pull بدترین پیامد Commit مخرب است که هنوز باید بازبینی شود و رد به‌جا می‌گذارد.
  • برای چهل Cluster لبه پشت NAT، فقط Pull مقیاس می‌گیرد؛ هر Cluster همان Repository را دریافت می‌کند.
جنبهPush؛ استقرار با CIPull؛ آشتی‌دهی با Agent
اعتبارنامهاعتبارنامهٔ Cluster در CIاعتبارنامهٔ خواندن Git/Registry داخل Cluster
شبکهCI باید به API server برسدCluster باید به Git/Registry برسد؛ فقط خروجی
Driftتا اجرای بعدی دیده نمی‌شوددر هر Reconciliation شناسایی می‌شود
Pruneفقط اگر اسکریپت حذف کندprune: true آنچه از Git حذف شده پاک می‌کند
ممیزیلاگ CIتاریخچهٔ Git و رویدادهای Agent
سرعت تغییرهنگام اجرای Job فوری استبازهٔ Poll یا Webhook؛ در حد ثانیه

راه‌حل: kubectl apply را از CI خارج کنید؛ Workflow قبل در Go را ببینید. به CI حق نوشتن در Config repository یا بازکردن PR بدهید و Agent را داخل Cluster قرار دهید.

وضعیت مطلوب، حلقهٔ آشتی‌دهی و انحراف (Desired state, reconciliation loop, drift) حیاتی ​

به زبان ساده: Agent سه کار را همیشه تکرار می‌کند: خواسته را می‌خواند، وضعیت موجود را می‌بیند و آن را با خواسته یکسان می‌کند.

بدفهمی رایج: «Reconciliation هنگام Push رخ می‌دهد.» Push یا Webhook فقط نوبت بعدی حلقه را جلو می‌اندازد. OpenGitOps می‌گوید "in GitOps, reconciliation is triggered whenever there is a divergence" و این واگرایی "could be due to the actual state unintentionally drifting from the desired state declarations – not only due to a new desired state declaration version having been changed intentionally."

تعریف: آشتی‌دهی (Reconciliation) یعنی "The process of ensuring the actual state of a system matches its desired state." انحراف (Drift) یعنی "When a system's actual state has moved or is in the process of moving away from the desired state". این حلقهٔ کنترل، بازخورد (Feedback) دارد؛ OpenGitOps "follows control-theory and operates in a closed-loop".

text
reconcile(app), every interval or on an event
1  fetch source at revision R (Git commit / OCI digest)       -> artifact
2  render: kustomize build | helm template | plain YAML         -> desired objects D
3  read live objects L that the app owns (tracking label/annotation)
4  diff(D, L) ignoring server-set fields and ignore rules
5  if diff and policy allows: apply (create/patch), prune objects in L but not in D
6  wait for health (rollout complete, Jobs succeeded) -> report status, emit events
7  requeue after interval; a new revision or a webhook requeues immediately

سناریوهای واقعی:

  • HPA یک Deployment را به هفت نمونه (Replica) می‌رساند، ولی Manifest در Git دو Replica می‌خواهد؛ بدون قاعدهٔ Ignore یا حذف replicas، هر دور حلقه با HPA درگیر می‌شود.
  • Webhook تغییردهنده، مانند تزریق‌کنندهٔ Sidecar در Service mesh، کانتینر اضافه می‌کند؛ Diff باید فیلدهای متعلق به Controller دیگر را نادیده بگیرد.
  • Operator گواهی Secret تحت مدیریت خود را تعویض می‌کند؛ آن Secret اصلاً نباید در Git باشد.
محصولمحرک حلقهتنظیم بازه
Argo CDPoll، Webhook گیت روی /api/webhook، Refresh دستیtimeout.reconciliation با پیش‌فرض 120 s و timeout.reconciliation.jitter برابر 60 s در argocd-cm
Flux Kustomization.spec.interval، Revision تازهٔ منبع، Webhook با Receiver، flux reconcile.spec.interval اجباری؛ "minimum value should be 60 seconds"؛ .spec.retryInterval
منابع Flux.spec.interval هر GitRepository/OCIRepositoryهمان تنظیم

راه‌حل: فیلد متعلق به Controller دیگر، مثل replicas زیر HPA، را در Git ننویسید یا برایش Ignore تعریف کنید. Webhook را تنظیم کنید تا Poll پشتیبان باشد، نه مسیر اصلی تحویل. مدل کوچک Drift در Go قابل اجراست.

چیدمان Repository: Config repository، App repository، Monorepo و پوشه‌های محیط حیاتی ​

به زبان ساده: پیکربندی استقرار را در Repository خودش بگذارید؛ روی یک شاخه برای هر محیط یک پوشه بسازید و تفاوت‌ها را با Overlay بیان کنید.

بدفهمی رایج: «شاخهٔ جدا برای هر محیط، مثل dev، staging و prod، روش طبیعی Git است.» این ضدالگوی شاخهٔ هر محیط (Branches per environment anti-pattern) است: تفاوت محیط‌ها در تاریخچهٔ Merge پنهان می‌شود، Cherry-pickها از هم دور می‌شوند و Merge از Staging به Prod تغییر نامرتبط را هم می‌برد. دیگر نمی‌توان با یک فرمان تفاوت Prod را دید. راهنمای Monorepo در Flux می‌گوید "The various environments specific configs are all stored in the same branch (e.g. main)"؛ شاخه‌های دیگر کوتاه‌عمرند: "once a pull request is merged, the branch gets deleted."

تعریف: Repository برنامه (App repository) کد و شاید Base manifest یا بستهٔ Helm (Chart) را نگه می‌دارد؛ Repository پیکربندی (Config repository) وضعیت مطلوب قابل استقرار یک یا چند برنامه و Cluster را نگه می‌دارد. توصیهٔ Argo CD برای جداسازی Config repository عبارت "highly recommended" است: جدایی کد و پیکربندی، "Cleaner audit log"، برنامهٔ ساخته‌شده از چند Repository، "Separation of access" و جلوگیری از "an infinite loop of build jobs and Git commit triggers". راهنمای Flux چهار چیدمان دارد: Monorepo، repo برای هر محیط، هر تیم یا هر برنامه. پوشهٔ هر محیط (Per-environment directories) از لایه‌های پوششی Kustomize (Kustomize overlays) با Base و overlays/staging و overlays/prod یا Helm values per env با values-staging.yaml و values-prod.yaml استفاده می‌کند؛ آموزش هر دو در بسته‌بندی Kubernetes است.

text
shop-config/                       (this chapter's snippet tree, docs/snippets/platform/gitops-argocd-flux/config-repo)
  apps/orders-api/base/            Go service: Deployment, Service, image name
  apps/orders-api/overlays/staging namespace, 1 replica, tag 1.5.0 (Image Updater writes here)
  apps/orders-api/overlays/prod    namespace, tag 1.4.2 + digest (promotion PRs write here)
  apps/orders-api/overlays/preview no namespace: each PR Application sets orders-api-pr-<n>
  apps/shop-laravel/base/          web (php-fpm + Nginx) and worker Deployments, Service
  apps/shop-laravel/release-jobs/  migrate Job (PreSync), smoke Job (PostSync)
  apps/shop-laravel/overlays/*     tags with Flux $imagepolicy markers
  infrastructure/namespaces/       cluster-scoped objects, reconciled first
  argocd/                          AppProjects, Applications, ApplicationSets, cluster Secret, Image Updater, config maps
  clusters/staging, clusters/prod  Flux objects per cluster (bootstrap path)
  tenants/                         Flux multi-tenancy onboarding

سناریوهای واقعی:

  • افزایش Replica در Prod نباید Build بیست‌دقیقه‌ای برنامه را فعال کند؛ Config repo جدا، دو Pipeline را جدا نگه می‌دارد.
  • پیمانکار می‌تواند به App repo بنویسد ولی نباید Production را تغییر دهد. Repository جدا دسترسی جدا می‌دهد؛ حفاظت شاخه به‌تنهایی کافی نیست: "Git is not designed to restrict access to certain files in a repository".
  • تیم با کنترل سخت‌گیرانهٔ تغییر Prod، repo per environment انتخاب می‌کند؛ Repository اختصاصی Production که "limits the scope of changes".
  • تیم Platform مالک infrastructure/ و clusters/ است؛ تیم‌های برنامه با CODEOWNERS مالک apps/<name>/ هستند. در repo per team همین جدایی به Repositoryهای جدا منتقل می‌شود.
چیدمانمناسب براینکتهٔ مراقبت
Monorepo، پوشهٔ هر محیط، یک شاخهبیشتر تیم‌ها؛ همه‌چیز یکجا دیده می‌شودCODEOWNERS برای Prod؛ PR بزرگ تغییر Prod را پنهان می‌کند
repo هر محیطدسترسی سخت‌گیرانهٔ Prod و محیط مقررات‌محورPromotion با PR میان repoها؛ تغییر زیرساخت کندتر
repo هر تیمتیم Platform و تیم‌های مستقل برنامهPlatform باید هر repo را معرفی کند؛ GitRepository در Flux یا source repo در AppProject
repo هر برنامه؛ Manifest کنار کدمجموعهٔ کوچک یا کتابخانهٔ Manifest به‌عنوان Baseحلقهٔ Commit در CI و ممیزی شلوغ؛ Config repo باید ارجاع دهد، نه کپی
شاخهٔ هر محیطتوصیه نمی‌شودDrift ناشی از Merge، تفاوت پنهان و شاخهٔ بلندعمر

این درخت هر دو سمت Argo CD یعنی argocd/ و Flux یعنی clusters/ و tenants/ را دارد تا رفتار دو ابزار روی Overlay یکسان دیده شود. آن‌ها جایگزین هم‌اند: در Cluster واقعی هر Namespace یک Agent دارد؛ دو Agent که shop-staging را آشتی‌دهی کنند بر سر همهٔ اشیا رقابت می‌کنند.

راه‌حل: از Monorepo بالا شروع کنید: فقط main، Overlay هر محیط، CODEOWNERS روی overlays/prod و argocd/ و کار CI برای رندر تمام Overlayها در هر PR. تست سیاست‌ها در Go است.

معماری Argo CD: api-server، repo-server، application-controller و Redis حیاتی ​

به زبان ساده: سه پردازهٔ اصلی (Processes) داریم: یکی پاسخ‌گوی انسان و ابزار، یکی رندرکنندهٔ Manifest از Git و یکی مسئول مقایسه و Sync. Redis حافظهٔ نهان (Cache) است.

بدفهمی رایج: «Argo CD از API server خودش Apply می‌کند، پس برای استقرار UI باید بالا باشد.» application-controller مستقل Reconciliation می‌کند؛ api-server برای کاربر، CLI، CI و Webhook است.

تعریف، طبق صفحهٔ معماری Argo CD: api-server "is a gRPC/REST server which exposes the API consumed by the Web UI, CLI, and CI/CD systems". مدیریت برنامه، "invoking of application operations (e.g. sync, rollback, user-defined actions)"، مدیریت اعتبارنامهٔ "stored as K8s secrets"، احراز هویت و واگذاری آن، "RBAC enforcement" و "listener/forwarder for Git webhook events" بر عهدهٔ آن است. repo-server "maintains a local cache of the Git repository holding the application manifests" و Manifest را از URL، Revision، مسیر برنامه و "template specific settings: parameters, helm values.yaml" می‌سازد. application-controller "continuously monitors running applications and compares the current, live state against the desired target state ... It detects OutOfSync application state and optionally takes corrective action" و Hookهای "(PreSync, Sync, PostSync)" را اجرا می‌کند. دربارهٔ Redis در مستندات HA آمده: "Redis is only used as a disposable cache and can be safely rebuilt without service disruption". کنار این‌ها argocd-dex-server برای SSO، ApplicationSet controller و notifications controller اجرا می‌شوند.

Web UI, argocd CLI,CI, Git webhooksGit / Helm repo /OCI registrynamespace argocdargocd-serverapi-server: gRPC/REST, RBAC,SSO, sync/rollback, webhooksdex-server(or direct OIDC)repo-serverclone + cache, render:kustomize build, helm template,plain YAML, pluginsapplication-controllerdiff desired vs live, syncwaves + hooks, self-heal,sync + health statusredis (cache)applicationset-controllernotifications-controllerKubernetesAPI (this orremote clusters)live statemanifestsoperations
text
Webhook-triggered sync of orders-api-staging
1  GitHub -> POST https://argocd.acme.internal/api/webhook (argocd-server)
2  argocd-server: refresh apps whose source repo matches
3  application-controller: ask repo-server for manifests of path overlays/staging at main@c4f1e9a
4  repo-server: git fetch (cached), kustomize build -> manifests (cached by revision)
5  controller: diff vs live objects (watched through its cluster cache) -> OutOfSync
6  automated sync: waves/hooks, kubectl-equivalent apply -> Synced, health Progressing -> Healthy
7  notifications-controller: trigger conditions evaluated -> Slack message if a trigger fires

سناریوهای واقعی:

  • تغییر Monorepo با صدها برنامهٔ Helm مصرف CPU در repo-server را بالا می‌برد؛ Replicaهای آن را بیشتر کنید. کلید Cache بر اساس Revision است.
  • یک نمونه (Instance) از Argo CD سی Cluster را اداره می‌کند؛ حافظهٔ application-controller با منابع تحت مشاهده رشد می‌کند. مستندات HA تقسیم Controller به بخش‌ها (Sharding) بر اساس Cluster را توضیح می‌دهند.
  • Redis از دست می‌رود؛ داده‌ای از دست نمی‌رود و فقط Cache بازسازی می‌شود.
مؤلفهWorkloadروش افزایش ظرفیت
argocd-serverDeploymentReplicaها؛ بدون وضعیت
argocd-repo-serverDeploymentReplicaها؛ رندر به CPU محدود است
argocd-application-controllerStatefulSetShardها؛ تقسیم Clusterها میان Replicaها
argocd-redisDeployment؛ در Manifestهای HA از Redis HACache دورریختنی
argocd-dex-serverDeploymentفقط هنگام استفاده از Dex
کنترل‌گرهای ApplicationSet و NotificationsDeploymentهامعمولاً یکی از هرکدام

راه‌حل: برای Production از Manifestهای دسترس‌پذیری بالا (HA) استفاده کنید؛ argocd-server را پشت ورودی شبکه (Ingress) با SSO بگذارید، Webhook گیت را تنظیم کنید و پیکربندی خود Argo CD، شامل Project، RBAC و ConfigMap اعلان‌ها، را هم در Git نگه دارید.

Application CRD و AppProject حیاتی ​

به زبان ساده: Application می‌گوید «این مسیر از این repo را رندر کن و در آن Namespace از آن Cluster نگه دار». AppProject تعیین می‌کند Applicationهایش از کدام repo، Cluster، Namespace و Kind استفاده کنند.

بدفهمی رایج: «Project با نام default کافی است.» این Project "permits deployments from any source repo, to any cluster, and all resource Kinds". توصیهٔ مستندات این است: "to create dedicated projects with explicit source, destination, and resource permissions." همچنین "Projects which can deploy to the Argo CD namespace grant admin access".

تعریف: Application CRD با تعریف "A group of Kubernetes resources as defined by a manifest. This is a Custom Resource Definition (CRD)." شامل spec.source با repoURL، targetRevision، path و گزینه‌های kustomize/helm/directory، spec.destination با server یا name و namespace، spec.project، spec.syncPolicy و spec.ignoreDifferences است. AppProject "is the Kubernetes resource object representing a logical grouping of applications" و با sourceRepos، destinations و roles به‌علاوهٔ فهرست اجازه/منع منابع Cluster و Namespace و syncWindows تعریف می‌شود.

text
Who may deploy what (shop project)
1  Application orders-api-prod: project shop, source shop-config.git, destination shop-prod
2  application-controller checks project shop: source repo allowed?      yes
3                                              destination allowed?       yes (shop-prod)
4                                              every kind allowed?        Deployment yes, ClusterRole no
5  a PR adding a ClusterRoleBinding to the overlay -> sync refused for that resource

سناریوهای واقعی:

  • Application تیم اشتباهی به kube-system اشاره می‌کند؛ destinations در Project آن را رد می‌کند.
  • Chart بی‌سروصدا ClusterRole اضافه می‌کند؛ clusterResourceWhitelist: [] مانع می‌شود و نویسندهٔ PR می‌فهمد این منبع باید در لایهٔ Platform باشد.
  • CI فقط باید Sync در Staging را فعال کند؛ نقش Project با applications, sync, shop/*-staging و Token از JWT کافی است؛ دسترسی دیگری لازم نیست.
فیلدمقدار Project فروشگاهدلیل
sourceReposفقط shop-config.gitهیچ برنامه‌ای YAML را از repo دلخواه نمی‌گیرد
destinationsshop-staging، shop-prodهرگز argocd؛ دسترسی مدیریتی می‌دهد
clusterResourceWhitelist[]Namespace و CRD از لایهٔ Platform می‌آیند
namespaceResourceWhitelistDeployment، ReplicaSet، Pod، Service، ConfigMap، Job، HPA، PDBدرخت UI را هم محدود می‌کند
rolesci-sync-stagingToken با حوزهٔ محدود برای CI
syncWindowsاجازهٔ Prod در روزهای کاری 06:00-18:00، manualSync: trueAgent پنجرهٔ تغییر را اعمال می‌کند

راه‌حل: برای هر تیم یا دامنه (Domain) یک Project بسازید؛ فقط Project مربوط به Platform اجازهٔ ورود به argocd داشته باشد:

yaml
# AppProject: the guard rails for every shop Application. Never deploy apps through
# the "default" project, which allows any repo, any cluster and every kind.
apiVersion: argoproj.io/v1alpha1
kind: AppProject
metadata:
  name: shop
  namespace: argocd
  finalizers:
    - resources-finalizer.argocd.argoproj.io
spec:
  description: Shop services (orders-api, shop-laravel)
  # only the config repository may be a source
  sourceRepos:
    - https://github.com/acme/shop-config.git
  # only the shop namespaces; never the argocd namespace (that would be admin access)
  destinations:
    - namespace: shop-staging
      server: https://kubernetes.default.svc
    - namespace: shop-prod
      server: https://prod-api.k8s.acme.internal
  # no cluster-scoped kinds at all: namespaces come from the platform layer
  clusterResourceWhitelist: []
  namespaceResourceWhitelist:
    - group: apps
      kind: Deployment
    - group: apps
      kind: ReplicaSet
    - group: ''
      kind: Pod
    - group: ''
      kind: Service
    - group: ''
      kind: ConfigMap
    - group: batch
      kind: Job
    - group: autoscaling
      kind: HorizontalPodAutoscaler
    - group: policy
      kind: PodDisruptionBudget
  roles:
    # CI may sync staging apps (for an explicit "deploy now"), nothing else
    - name: ci-sync-staging
      description: Sync privileges for staging Applications only
      policies:
        - p, proj:shop:ci-sync-staging, applications, sync, shop/*-staging, allow
  # prod changes only between 06:00 and 18:00 UTC on weekdays; manual syncs stay possible
  syncWindows:
    - kind: allow
      schedule: "0 6 * * 1-5"
      duration: 12h
      applications:
        - "*-prod"
      manualSync: true
yaml
# Two more projects. "platform" may manage Argo CD's own namespace, which makes it
# admin-level: only platform admins push to argocd/ and sync this project.
# "shop-previews" may deploy only into orders-api-pr-* namespaces.
apiVersion: argoproj.io/v1alpha1
kind: AppProject
metadata:
  name: platform
  namespace: argocd
spec:
  description: Argo CD's own objects (projects, ApplicationSets, Applications)
  sourceRepos:
    - https://github.com/acme/shop-config.git
  destinations:
    - namespace: argocd
      server: https://kubernetes.default.svc
  clusterResourceWhitelist: []
  namespaceResourceWhitelist:
    # cluster registration Secrets (argocd.argoproj.io/secret-type: cluster)
    - group: ''
      kind: Secret
    - group: argoproj.io
      kind: AppProject
    - group: argoproj.io
      kind: Application
    - group: argoproj.io
      kind: ApplicationSet
    - group: argocd-image-updater.argoproj.io
      kind: ImageUpdater
---
apiVersion: argoproj.io/v1alpha1
kind: AppProject
metadata:
  name: shop-previews
  namespace: argocd
spec:
  description: Short-lived pull-request environments for orders-api
  sourceRepos:
    - https://github.com/acme/shop-config.git
  destinations:
    - namespace: 'orders-api-pr-*'
      server: https://kubernetes.default.svc
  # CreateNamespace=true needs Namespace in the cluster-scoped allow list
  clusterResourceWhitelist:
    - group: ''
      kind: Namespace
  namespaceResourceWhitelist:
    - group: apps
      kind: Deployment
    - group: apps
      kind: ReplicaSet
    - group: ''
      kind: Pod
    - group: ''
      kind: Service

سیاست Sync: همگام‌سازی خودکار، Prune، selfHeal و گزینه‌ها حیاتی ​

به زبان ساده: همگام‌سازی خودکار (Automated sync) خودش Commit تازه را اعمال می‌کند؛ هرس (Prune) آنچه از Git برداشته‌اید حذف می‌کند؛ خود‌ترمیمی (Self-heal) تغییر داخل Cluster را هم برمی‌گرداند.

بدفهمی رایج: «automated: {}، GitOps کامل می‌دهد.» سه پیش‌فرض محافظتی باقی می‌ماند: Prune خاموش است، چون "By default (and as a safety mechanism), automated sync will not delete resources when Argo CD detects the resource is no longer defined in Git"؛ Self-heal خاموش است؛ برنامهٔ خالی هم مجاز نیست، چون "automated sync with prune have a protection from any automation/human errors when there are no target resources"، مگر با allowEmpty: true.

تعریف: spec.syncPolicy.automated، Automated sync را روشن می‌کند؛ enabled: false فیلدها را نگه می‌دارد ولی اجرا را متوقف می‌کند. prune: true منابع اضافی را حذف می‌کند. selfHeal: true هنگام "when the live cluster's state deviates from the state defined in Git"، Sync می‌کند و تلاش بعدی "after self-heal timeout (5 seconds by default)" است؛ تنظیم آن --self-heal-timeout-seconds است. retry عقب‌نشینی (Backoff) را با limit، backoff.duration، factor و maxDuration تعیین می‌کند. بدون آن، مرجع Application می‌گوید "automated sync by default retries failed attempts 5 times with following delays between attempts ( 5s, 10s, 20s, 40s, 80s )". Automated sync فقط "only if the application is OutOfSync" اجرا می‌شود و "will only attempt one synchronization per unique combination of commit SHA1 and application parameters"، مگر Self-heal روشن باشد. پس از اتمام تلاش‌ها، "Automatic sync will not reattempt a sync if the previous sync attempt against the same commit-SHA and parameters had failed"؛ Commit تازه یا Sync دستی لازم است. گزینه‌های Sync (Sync options) در syncOptions یا Annotation هر منبع با argocd.argoproj.io/sync-options قرار می‌گیرند: Prune=false، Prune=confirm، Delete=false، Validate=false، SkipDryRunOnMissingResource=true، ApplyOutOfSyncOnly=true، PrunePropagationPolicy=foreground|background|orphan، PruneLast=true، Replace=true که می‌تواند مخرب باشد، Force=true همراه Replace، ServerSideApply=true با اجرای kubectl apply --server-side --force-conflicts، FailOnSharedResource=true، RespectIgnoreDifferences=true و CreateNamespace=true.

text
Same commit, three policies; someone ran kubectl scale deploy/orders-api --replicas=0
                       automated:{}           +prune             +selfHeal
1 new commit arrives   synced                 synced             synced
2 manifest deleted     resource stays (OOS)   resource deleted   resource deleted
3 kubectl scale 0      OutOfSync, no action   OutOfSync, no act. re-synced after ~5 s

سناریوهای واقعی:

  • PersistentVolumeClaim باید پس از حذف برنامه بماند؛ روی آن Delete=false بگذارید.
  • Namespace نباید تصادفی Prune شود؛ Prune=confirm بگذارید.
  • CRD بزرگ از سقف ۲۶۲۱۴۴ بایتی حاشیه‌نویسی (Annotation) با نام last-applied-configuration می‌گذرد؛ ServerSideApply=true استفاده کنید.
  • دو Application یک ConfigMap را رندر می‌کنند؛ FailOnSharedResource=true رقابت خاموش را به Sync ناموفق تبدیل می‌کند.
فیلد یا گزینهٔ سیاستپیش‌فرضزمان استفاده
automatedخاموشهر محیطی که باید بدون کلیک Git را دنبال کند
automated.prunefalseهمیشه در GitOps؛ اشیای خاص را با Prune=false/confirm محافظت کنید
automated.selfHealfalseProduction بدون تغییر دستی؛ زمان خاموش‌کردن را ببینید
automated.allowEmptyfalseبه‌ندرت؛ پیش‌فرض جلوی حذف همه‌چیز با Commit بد را می‌گیرد
retry.limitAutomated sync: تعداد 5 تلاش در 5/10/20/40/80 sصریح بنویسید، مانند limit: 5 و maxDuration: 3m، تا رفتار در Git دیده شود؛ -1 نامحدود است
ServerSideApply=trueApply سمت Clientاشیای بزرگ و مالکیت مشترک فیلد
ApplyOutOfSyncOnly=trueApply همهٔ اشیابرنامه با هزاران شیء
CreateNamespace=trueنبود Namespace باعث شکست استمحیط موقت مثل Preview؛ نه وقتی Platform مالک Namespace است

راه‌حل: Application کامل سرویس Go برای Prod در ادامه آمده است. ApplicationSet فروشگاه هم همین شیء را می‌سازد؛ بنابراین root app این فایل را مستثنا می‌کند. در Repository واقعی یکی از این دو روش را نگه دارید:

yaml
# The Go service in prod as one Argo CD Application, written out by hand to show every
# field. In this repository the shop ApplicationSet generates the same Application, so
# the root app excludes this file; use one or the other, never both.
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: orders-api-prod
  namespace: argocd
  finalizers:
    # deleting the Application deletes its resources (cascading delete)
    - resources-finalizer.argocd.argoproj.io
  annotations:
    notifications.argoproj.io/subscribe.on-sync-failed.slack: shop-deploys
    notifications.argoproj.io/subscribe.on-health-degraded.slack: shop-deploys
spec:
  project: shop
  source:
    repoURL: https://github.com/acme/shop-config.git
    targetRevision: main
    path: apps/orders-api/overlays/prod
  destination:
    server: https://prod-api.k8s.acme.internal
    namespace: shop-prod
  syncPolicy:
    automated:
      # delete objects that were removed from Git
      prune: true
      # revert manual changes in the cluster (drift) without waiting for a new commit
      selfHeal: true
    syncOptions:
      - ServerSideApply=true
      - PruneLast=true
      # the namespace comes from the platform layer, not from this app
      - CreateNamespace=false
    retry:
      limit: 5
      backoff:
        duration: 5s
        factor: 2
        maxDuration: 3m
  # an HPA owns spec.replicas in prod; do not report it as drift
  ignoreDifferences:
    - group: apps
      kind: Deployment
      jsonPointers:
        - /spec/replicas
  revisionHistoryLimit: 10

موج‌ها و قلاب‌های Sync: PreSync، PostSync، SyncFail، PreDelete و PostDelete حیاتی ​

به زبان ساده: قلاب (Hook)، Job را قبل، بعد یا به‌جای یک مرحلهٔ Sync اجرا می‌کند؛ Migration قبل و Smoke test بعد. موج (Wave) منابع عادی را با عدد مرتب می‌کند.

بدفهمی رایج: «Hookهای Helm زیر Argo CD همان رفتار Helm را دارند.» Argo CD با helm template رندر می‌کند و Annotationهای Helm hook را به فازهای خودش نگاشت می‌کند: "delete-policy evaluation still follows Argo CD sync phases and sync result semantics rather than Helm's per-hook-event lifecycle."

تعریف: argocd.argoproj.io/hook فاز منبع را مشخص می‌کند: PreSync یعنی "Executes prior to the application of the manifests"؛ Sync، "at the same time as the application of the manifests"؛ Skip؛ PostSync، "Executes after all Sync hooks completed and were successful, a successful application, and all resources in a Healthy state"؛ SyncFail، "Executes when the sync operation fails"؛ PreDelete و PostDelete فقط هنگام حذف Application اجرا می‌شوند؛ PostDelete، "Available starting in v2.10" است. argocd.argoproj.io/hook-delete-policy یکی از HookSucceeded، HookFailed یا BeforeHookCreation است؛ آخری در صورت نبود مقدار، پیش‌فرض است. موج‌های همگام‌سازی (Sync waves) با argocd.argoproj.io/sync-wave عدد صحیح دارند؛ پیش‌فرض صفر است و منفی هم مجاز است. Argo CD کمترین Wave را اعمال می‌کند، منتظر سلامت می‌ماند و سپس سراغ بعدی می‌رود. "The current delay between each sync wave is 2 seconds" با ARGOCD_SYNC_WAVE_DELAY تنظیم می‌شود. Prune ترتیب معکوس دارد. Hookها "do not run during a selective sync operation".

text
Sync of shop-laravel-staging at commit 9a1b (tag 2.8.1 -> 2.9.0)
1  PreSync   Job shop-migrate: php artisan migrate --force --isolated     -> Succeeded
2  Sync      wave 0: Service, Deployments shop-web + shop-worker (new image) applied
3            wait: Deployments Progressing -> Healthy (readiness /up green)
4  PostSync  Job shop-smoke: php artisan app:smoke-test                    -> Succeeded
5  sync result Succeeded; hooks with HookSucceeded deleted
   if step 1 fails: whole sync stops, nothing new is applied, SyncFail hooks run

سناریوهای واقعی:

  • Migration پایگاه داده پیش از Pod جدید با PreSync Job؛ باید با گذشته سازگار باشد چون Pod قدیمی حین Rollout همچنان پاسخ می‌دهد.
  • Smoke test پس از Rollout با PostSync؛ شکستش Sync را ناموفق می‌کند و با Trigger به نام on-sync-failed هشدار می‌دهد.
  • CRD در Wave منفی یک، Operator در Wave صفر و منابع سفارشی آن در Wave یک.
  • حذف رکورد DNS از سیستم بیرونی هنگام حذف برنامه با PostDelete.
موضوعArgo CDFlux
مراحل قبل و بعدPreSync / PostSync / SyncFailفاز ندارد؛ Kustomization جدا با dependsOn یا Helm hook داخل HelmRelease واقعی
ترتیب منابع عادیSync wavesdependsOn میان Kustomizationها؛ مثال مستندات: CRDها و Controller مربوط به cert-manager پیش از certs
اجرای دوبارهٔ Jobساخت دوبارهٔ Hook در هر Sync با BeforeHookCreationقالب Job تغییرناپذیر است؛ kustomize.toolkit.fluxcd.io/force: enabled آن را دوباره می‌سازد
انتظار برای تکمیلHook باید Healthy شودwait: true یا حضور Job در healthChecks

راه‌حل: Jobهای انتشار Laravel که هر دو Agent می‌خوانند:

yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: shop-migrate
  annotations:
    # Argo CD: run before any manifest of the sync is applied; a failure stops the sync
    argocd.argoproj.io/hook: PreSync
    # delete the previous run just before creating the new one (also Argo CD's default)
    argocd.argoproj.io/hook-delete-policy: BeforeHookCreation
    # Flux: Job templates are immutable; recreate the Job when the image tag changes
    kustomize.toolkit.fluxcd.io/force: enabled
spec:
  backoffLimit: 1
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: migrate
          image: ghcr.io/acme/shop-app
          # --force: no confirmation prompt in production; --isolated: a cache lock so two
          # concurrent runs (two clusters, a retried sync) never migrate at the same time
          command: ["php", "artisan", "migrate", "--force", "--isolated"]
          envFrom:
            - secretRef:
                name: shop-laravel-env
yaml
apiVersion: batch/v1
kind: Job
metadata:
  name: shop-smoke
  annotations:
    # Argo CD: run after every resource is applied and Healthy; failure marks the sync failed,
    # which fires the on-sync-failed notification trigger
    argocd.argoproj.io/hook: PostSync
    argocd.argoproj.io/hook-delete-policy: HookSucceeded
    kustomize.toolkit.fluxcd.io/force: enabled
spec:
  # Ordering does not come from retries: the command itself first polls the web Service's
  # /version until it reports this image's version (needed under Flux, which has no hook
  # phases), then checks DB, schema and cache. One retry covers a pod eviction.
  backoffLimit: 1
  template:
    spec:
      restartPolicy: Never
      containers:
        - name: smoke
          image: ghcr.io/acme/shop-app
          command: ["php", "artisan", "app:smoke-test", "--url=http://shop-web"]
          envFrom:
            - secretRef:
                name: shop-laravel-env

وضعیت سلامت: Healthy، Progressing، Degraded؛ و تفاوت OutOfSync حیاتی ​

به زبان ساده: وضعیت همگام‌سازی (Sync status) پاسخ می‌دهد «Cluster با Git یکسان است؟»؛ سلامت (Health) می‌پرسد «کار می‌کند؟». برنامه می‌تواند Synced و Degraded یا OutOfSync و Healthy باشد.

بدفهمی رایج: «Synced یعنی استقرار موفق.» Synced فقط یکسانی اشیا را می‌گوید؛ Pod تازه شاید در CrashLoopBackOff باشد. Health را ببینید؛ در Flux هم Ready همراه wait: true را بررسی کنید.

تعریف: مفاهیم Argo CD، Sync status را "Whether or not the live state matches the target state" و Health را "is it running correctly? Can it serve requests?" تعریف می‌کنند. در بررسی داخلی Deployment، ReplicaSet، StatefulSet و DaemonSet باید Generation مشاهده‌شده با مطلوب و تعداد Replicaهای به‌روزشده با مطلوب برابر باشد. Pod با restartPolicy: Always اگر کانتینرش در وضعیت خطای "(e.g. CrashLoopBackOff, ImagePullBackOff)" باشد، "Degraded" است. Pod شبیه Job، "is considered 'Progressing' while it is running". وضعیت‌ها Healthy، Progressing با معنای "not healthy yet but still making progress"، Degraded، Suspended، Missing و Unknown هستند. "The App health will be the worst health of its immediate child resources". منابع سفارشی به بررسی Lua در resource.customizations.health.<group>_<kind> نیاز دارند. Health check در Flux، Kindهای داخلی، Kindهای Flux و "Custom resources that are compatible with kstatus" را می‌پذیرد.

text
Rollout of orders-api 1.5.0 with a bad config value
t0   sync applies Deployment (generation 9 -> 10)        sync: Synced   health: Progressing
t+40 new pods CrashLoopBackOff, old ReplicaSet still up  sync: Synced   health: Degraded
t+41 on-health-degraded trigger -> Slack                 (Flux: Kustomization Ready=False, HealthCheckFailed)
t+60 fix = revert commit -> new sync                     sync: Synced   health: Healthy

سناریوهای واقعی:

  • Deployment با Probe همیشه ناموفق تا progressDeadlineSeconds در Progressing می‌ماند، سپس Degraded می‌شود.
  • والد app of apps ممکن است Healthy باشد و فرزند Degraded؛ بررسی Health برای Application در نسخهٔ 1.8 حذف شد. مستندات برای بازگرداندنش تنظیم Lua می‌دهند.
  • Kustomization بدون wait یا healthChecks، بلافاصله پس از Apply و پیش از شروع Pod، Ready گزارش می‌کند.
وضعیتعبارت Argo CDمعادل Flux
Healthy"the resource is healthy"Ready=True پس از Health check
Progressing"not healthy yet but still making progress"Ready=Unknown با دلیل Progressing
Degraded"the resource is degraded"Ready=False با دلیل HealthCheckFailed
Suspended"waiting for some external event to resume".spec.suspend: true؛ توقف Reconciliation
OutOfSyncوضعیت زنده با هدف متفاوت استاصلاح Drift در بازهٔ بعد؛ وضعیت جدا ندارد

راه‌حل: برای هر Workload، Probe آمادگی واقعی بگذارید؛ /readyz برای Go و /up برای Laravel. در Flux، wait: true یا healthChecks را تنظیم کنید و مشترک on-health-degraded شوید.

محاسبهٔ تفاوت (Diffing) و ignoreDifferences مهم ​

به زبان ساده: بعضی فیلدها به‌درستی توسط دیگری تغییر می‌کنند؛ به Agent بگویید آن‌ها را Drift حساب نکند.

بدفهمی رایج: «OutOfSync بلافاصله پس از Sync موفق یعنی Argo CD خراب است.» علت‌های رایج در مستندات: فیلد ناشناختهٔ اضافی در Manifest که API server حذف می‌کند، Prune خاموش، "A controller or mutating webhook is altering the object"، استفادهٔ Chart از randAlphaNum یا مرتب‌سازی دوبارهٔ spec.metrics توسط HPA.

تعریف: spec.ignoreDifferences، group و kind، name/namespace اختیاری و jsonPointers را می‌گیرد؛ طبق RFC ۶۹۰۲، / در کلید با ~1 نوشته می‌شود. جایگزین‌ها jqPathExpressions و managedFieldsManagers هستند؛ آخری مثلاً فیلدهای متعلق به kube-controller-manager را نادیده می‌گیرد. تنظیم سراسری در resource.customizations.ignoreDifferences.<group>_<kind> یا .all داخل argocd-cm است. resource.compareoptions با ignoreResourceStatusField مقادیر crd، all به‌عنوان پیش‌فرض و none دارد. پیش‌فرض Ignore فقط بر مقایسه اثر می‌گذارد: "during the sync stage, the desired state is applied as-is"، مگر RespectIgnoreDifferences=true باشد. HelmRelease در Flux، driftDetection.ignore با JSON pointer دارد؛ برای Kustomization فیلد متعلق به دیگری را در Git ننویسید.

text
HPA vs Git, Application with and without ignoreDifferences on /spec/replicas
1  Git: replicas: 2     HPA scales to 7
2  no rule:   OutOfSync; with selfHeal the agent sets 2, the HPA sets 7 again ... (flapping)
3  rule:      Synced; HPA owns the field
4  better:    omit replicas from Git entirely (Argo CD best practice: "do not include replicas")

سناریوهای واقعی:

  • Istio یا Linkerd کانتینر همراه (Sidecar) تزریق می‌کنند؛ با jqPathExpressions کانتینر تزریقی را انتخاب کنید یا از managedFieldsManagers استفاده کنید.
  • cert-manager مقدار caBundle در MutatingWebhookConfiguration را تعویض می‌کند؛ مثال سراسری مستندات همین است.
  • Operator در CR ثبت‌شده در Git، status می‌نویسد؛ ignoreResourceStatusField: crd مناسب است.
نیازArgo CDFlux
نادیده‌گرفتن یک فیلدignoreDifferences.jsonPointersdriftDetection.ignore.paths در HelmRelease
نادیده‌گرفتن فیلد Controller دیگرmanagedFieldsManagersمالکیت فیلد در Server-side apply؛ آن فیلدها را ننویسید
دست‌نخوردن فیلد هنگام Sync همRespectIgnoreDifferences=truekustomize.toolkit.fluxcd.io/ssa: IfNotPresent؛ فقط ایجاد
دست‌نخوردن فیلدهای یک شیء هنگام SyncignoreDifferences همراه RespectIgnoreDifferences=true؛ Prune=false فقط حذف را می‌بندد و Sync هنوز وضعیت مطلوب را Apply می‌کند؛ یا شیء را از منبع برنامه خارج کنیدkustomize.toolkit.fluxcd.io/reconcile: disabled؛ نه Apply و نه Prune

راه‌حل: ignoreDifferences در Application مربوط به Prod بالا را ببینید؛ حذف فیلد از Git انتخاب بهتر است.

ApplicationSet: مولدهای Git، Cluster، Matrix و Pull Request؛ app of apps حیاتی ​

به زبان ساده: به‌جای نوشتن Application برای هر ترکیب برنامه، محیط و Cluster، یک قالب بنویسید و ساخت پارامترها را به مولدها (Generators) بسپارید. App of apps روش قدیمی‌تر است: Application که Manifestهایش Applicationهای دیگرند.

بدفهمی رایج: «می‌توان ApplicationSet را با خیال راحت به هر تیم سپرد.» مستندات می‌گویند "only admins may be given permission ... to create, update, or delete ApplicationSets"، زیرا "can create Applications under arbitrary Projects" و Git generator، "can read Secrets in the Argo CD namespace and send them to arbitrary URLs". برای app of apps هم همین محدودیت هست: "App of Apps is an admin-only tool".

تعریف: Controller مربوط به ApplicationSet، از v2.3 همراه Argo CD است و spec.template را برای هر مجموعه‌پارامتر spec.generators رندر می‌کند. مولدها شامل List، Cluster با "based on the list of clusters defined within (and managed by) Argo CD"، Git با "based on files within a Git repository, or based on the directory structure"، Matrix با "combine the generated parameters of two separate generators"، Merge، SCM Provider، Pull Request با "automatically discover open pull requests within an repository"، Cluster Decision Resource، Plugin و OCI هستند. Git directory generator، path.path، path.basename، path.basenameNormalized و path.segments می‌دهد؛ Cluster generator، name، nameNormalized، server و metadata.labels.<key>؛ PR generator، number، branch، branch_slug، target_branch، head_sha، head_short_sha و labels می‌دهد و پیش‌فرض "every 30 minutes" با requeueAfterSeconds سرکشی می‌کند. Matrix، "currently only supports combining the outputs of only two child generators" و فرزند می‌تواند پارامتر فرزند قبلی را مصرف کند. با goTemplate: true و missingkey=error، غلط املایی رندر را شکست می‌دهد و Application با نام -staging نمی‌سازد. App of apps یعنی "Declaratively specify one Argo CD app that consists only of other apps". راهنمای Cluster bootstrapping، ApplicationSet با Cluster generator را توصیه می‌کند و app of apps را جایگزین می‌داند.

text
appset-shop: matrix(git directories apps/*/overlays/*, clusters with label env=<dir name>)
git child    -> {path: apps/orders-api/overlays/staging, basename: staging, segments: [apps,orders-api,overlays,staging]}
                {path: apps/orders-api/overlays/prod, ...} {path: apps/shop-laravel/overlays/staging, ...} {..prod..}
cluster child (per git item, selector env=<basename>) -> staging item: {name: in-cluster, server: https://kubernetes.default.svc}
matrix       -> orders-api-staging, orders-api-prod, shop-laravel-staging, shop-laravel-prod
new overlay apps/payments/overlays/staging pushed -> payments-staging appears at the next generator run
cluster Secret relabelled -> its Applications move or disappear (and are deleted with their resources)

سناریوهای واقعی:

  • دوازده سرویس در سه محیط، سی‌وشش Application از یک ApplicationSet می‌سازند؛ اضافه‌کردن سرویس یعنی افزودن پوشه.
  • Cluster منطقه‌ای تازه با برچسب env=prod ثبت می‌شود و بدون تغییر YAML تمام برنامه‌های Prod را دریافت می‌کند.
  • برای هر PR با برچسب preview محیط پیش‌نمایش ساخته و با بسته‌شدن PR حذف می‌شود.
  • در Bootstrap خوشه، root Application پوشهٔ argocd/ شامل Projectها و ApplicationSetها را Sync می‌کند.
مولدمنشأ پارامترهاکاربرد معمول
Listعناصر صریحچند Cluster یا Tenant ثابت
ClusterSecretهای Cluster در Argo CD با برچسب‌هاافزودنی‌ها برای هر Cluster عملیاتی
Git؛ پوشه یا فایلچیدمان repo یا فایل JSON/YAMLApplication برای هر پوشهٔ Overlay
Matrixحاصل‌ضرب دو فرزندبرنامه‌ها × Clusterها
Mergeمولد پایه با بازنویسی از دیگرانتغییر پیش‌فرض برای هر Cluster
Pull RequestPRهای باز GitHub، GitLab، Gitea، Bitbucket و غیرهمحیط Preview
SCM ProviderRepositoryهای سازمانیک برنامه برای هر Repository

راه‌حل: ApplicationSet فروشگاه، ApplicationSet پیش‌نمایش‌ها و root app:

yaml
# One ApplicationSet generates an <app>-<env> Application per overlay directory.
# Matrix of two children: the git directory generator discovers apps/*/overlays/* in the
# config repo; the cluster generator then picks the Argo CD cluster whose Secret carries
# the label env=<overlay name>. A new overlay or a new labelled cluster needs no new YAML.
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: shop
  namespace: argocd
spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  generators:
    - matrix:
        generators:
          # child 1 produces path.path, path.basename and path.segments
          - git:
              repoURL: https://github.com/acme/shop-config.git
              revision: main
              directories:
                - path: apps/*/overlays/*
          # child 2 consumes child 1's parameters (it must come second). The selector never
          # matches the default local cluster (it has no Secret): see cluster-staging.yaml
          - clusters:
              selector:
                matchLabels:
                  argocd.argoproj.io/secret-type: cluster
                  env: '{{.path.basename}}'
  # let on-call disable auto-sync on ONE generated Application during an incident:
  # without this rule the controller resets spec.syncPolicy to the template's value
  ignoreApplicationDifferences:
    - jsonPointers:
        - /spec/syncPolicy
  template:
    metadata:
      # path.segments is [apps, <app>, overlays, <env>]
      name: '{{index .path.segments 1}}-{{.path.basename}}'
      annotations:
        notifications.argoproj.io/subscribe.on-sync-failed.slack: shop-deploys
        notifications.argoproj.io/subscribe.on-health-degraded.slack: shop-deploys
    spec:
      project: shop
      source:
        repoURL: https://github.com/acme/shop-config.git
        targetRevision: main
        path: '{{.path.path}}'
      destination:
        server: '{{.server}}'
        namespace: 'shop-{{.path.basename}}'
      syncPolicy:
        automated:
          prune: true
          selfHeal: true
        syncOptions:
          - ServerSideApply=true
          - PruneLast=true
      ignoreDifferences:
        - group: apps
          kind: Deployment
          jsonPointers:
            - /spec/replicas
yaml
# Preview environments: one Application per open pull request labelled "preview" in the
# orders-api application repository. CI pushes an image tagged with the PR head SHA;
# the Application renders the preview overlay with that tag in its own namespace.
# Closing or merging the PR deletes the Application (and, through the finalizer, the env).
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: orders-api-previews
  namespace: argocd
spec:
  goTemplate: true
  goTemplateOptions: ["missingkey=error"]
  generators:
    - pullRequest:
        github:
          owner: acme
          repo: orders-api
          tokenRef:
            secretName: github-token
            key: token
          labels:
            - preview
        # without the ApplicationSet webhook, new PRs are found by polling (default 30 min)
        requeueAfterSeconds: 300
  template:
    metadata:
      name: 'orders-api-pr-{{.number}}'
      finalizers:
        - resources-finalizer.argocd.argoproj.io
    spec:
      # a fixed project (never templated from PR data) keeps a PR from widening its rights
      project: shop-previews
      source:
        repoURL: https://github.com/acme/shop-config.git
        targetRevision: main
        # the preview overlay sets no namespace; kustomize.namespace puts every object in
        # the PR namespace (destination.namespace alone only fills objects that have none)
        path: apps/orders-api/overlays/preview
        kustomize:
          namespace: 'orders-api-pr-{{.number}}'
          images:
            - 'ghcr.io/acme/orders-api:pr-{{.head_short_sha}}'
      destination:
        server: https://kubernetes.default.svc
        namespace: 'orders-api-pr-{{.number}}'
      syncPolicy:
        automated:
          prune: true
          selfHeal: true
        syncOptions:
          - CreateNamespace=true
yaml
# App of apps: the only Application created by hand (or by the bootstrap script).
# It syncs the argocd/ directory, which holds the AppProject, the ApplicationSets and
# the per-app Applications. Admin-only: whoever can push here can create Applications
# in any project, so the directory is protected by CODEOWNERS and branch protection.
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: root
  namespace: argocd
  finalizers:
    - resources-finalizer.argocd.argoproj.io
spec:
  project: platform
  source:
    repoURL: https://github.com/acme/shop-config.git
    targetRevision: main
    path: argocd
    directory:
      recurse: true
      # excluded: the ConfigMaps (applied with the Argo CD installation itself) and the
      # standalone orders-api-prod Application, which only illustrates what the shop
      # ApplicationSet generates (applying both would create the same Application twice)
      exclude: '{argocd-cm*.yaml,argocd-*-cm.yaml,app-orders-api-prod.yaml}'
  destination:
    server: https://kubernetes.default.svc
    namespace: argocd
  syncPolicy:
    automated:
      prune: true
      selfHeal: true

Selector در Cluster generator فقط Cluster دارای Secret را پیدا می‌کند. چون "the default local cluster does not have a Secret"، Cluster محلی را صریح و با برچسب env تعریف می‌کنیم:

yaml
# The local cluster declared as a cluster Secret so it can carry the env label.
# A selector on argocd.argoproj.io/secret-type never matches the default local cluster
# (it has no Secret), so without this the shop ApplicationSet would generate no
# staging Applications. The prod cluster is registered the same way (with credentials,
# kept out of Git: SOPS, Sealed Secrets or ESO) and labelled env: prod.
apiVersion: v1
kind: Secret
metadata:
  name: cluster-staging
  namespace: argocd
  labels:
    argocd.argoproj.io/secret-type: cluster
    env: staging
stringData:
  name: staging
  server: https://kubernetes.default.svc
  config: '{"tlsClientConfig":{"insecure":false}}'

RBAC، SSO و اعلان‌های Argo CD Notifications مهم ​

به زبان ساده: کاربران با ارائه‌دهندهٔ هویت شما وارد می‌شوند؛ قواعد Casbin تعیین می‌کنند چه کسی کدام برنامه را Sync یا Rollback کند؛ اعلان‌ها رخداد را به Slack، ایمیل، PagerDuty یا GitHub می‌رسانند.

بدفهمی رایج: «Argo CD RBAC جای Kubernetes RBAC را می‌گیرد.» فقط کار کاربر از طریق Argo CD را کنترل می‌کند. application-controller با ServiceAccount خودش Apply می‌کند؛ حقوق Kubernetes آن سقف عمل هر Application است؛ امنیت Kubernetes.

تعریف: برای ورود یکپارچه (SSO)، "There are two ways that SSO can be configured": ارائه‌دهندهٔ OIDC همراه Dex برای SAML، LDAP یا نگاشت سازمان/تیم GitHub؛ یا ارائه‌دهندهٔ OIDC موجود با oidc.config در argocd-cm. کاربر admin داخلی باید "only for initial configuration and then switch to local users or configure SSO integration" استفاده شود؛ سپس admin.enabled: "false". Argo CD RBAC در argocd-rbac-cm است: policy.default مانند role:readonly، scopes برای تعیین Claimهای گروه در Token و policy.csv با قالب p, <role/user/group>, <resource>, <action>, <object>, <effect> و g, <user/group>, <role>. نقش‌های داخلی role:readonly و role:admin هستند. Argo CD Notifications، argocd-notifications-cm را می‌خواند: service.<name>، template.<name> و trigger.<name> با عبارت when و قالب‌های send. اشتراک Application با notifications.argoproj.io/subscribe.<trigger>.<service>: <recipient> است. فهرست شامل on-created، on-deleted، on-deployed، on-health-degraded، on-sync-failed، on-sync-running، on-sync-status-unknown و on-sync-succeeded است.

text
Developer clicks "Sync" on orders-api-prod
1  browser -> argocd-server, OIDC token with groups [acme:shop-developers]
2  g, acme:shop-developers, role:shop-dev   -> role:shop-dev
3  p, role:shop-dev, applications, sync, shop/*-staging, allow  -> no match for shop/orders-api-prod
4  policy.default role:readonly -> sync denied (permission denied)
5  release manager (acme:shop-release-managers) -> role:shop-release -> allowed, inside the sync window

سناریوهای واقعی:

  • توسعه‌دهنده Staging را Sync و Rollback می‌کند؛ فقط مدیر انتشار به Prod دست می‌زند؛ مدیر Platform نقش role:admin دارد.
  • Sync ناموفق Prod همراه Revision و پیام عملیات به #shop-deploys فرستاده می‌شود.
  • وضعیت Commit در GitHub برای هر Sync، با قالب github-commit-status در مثال Triggerهای مستندات، وضعیت استقرار را روی Commit نشان می‌دهد.
فایلمحتوا
argocd-cmurl، oidc.config یا dex.config، admin.enabled، timeout.reconciliation، روش رهگیری و سفارشی‌سازی منابع
argocd-rbac-cmpolicy.default، policy.csv، scopes
argocd-notifications-cmسرویس‌ها، قالب‌ها، Triggerها و context
argocd-secret / Secretهای برچسب‌دارClient secretها و Tokenها با ارجاع $key

راه‌حل:

yaml
# Argo CD RBAC (Casbin syntax). SSO groups come from the OIDC "groups" claim.
apiVersion: v1
kind: ConfigMap
metadata:
  name: argocd-rbac-cm
  namespace: argocd
data:
  # everyone who logs in can look, nobody can change anything by default
  policy.default: role:readonly
  scopes: '[groups]'
  policy.csv: |
    # developers: sync and roll back staging apps of the shop project, read everything
    p, role:shop-dev, applications, get, shop/*, allow
    p, role:shop-dev, applications, sync, shop/*-staging, allow
    p, role:shop-dev, applications, rollback, shop/*-staging, allow
    p, role:shop-dev, logs, get, shop/*, allow
    # release managers: prod sync and rollback; still no create/delete of Applications
    p, role:shop-release, applications, sync, shop/*-prod, allow
    p, role:shop-release, applications, rollback, shop/*-prod, allow
    g, role:shop-release, role:shop-dev
    # map SSO groups to roles
    g, acme:shop-developers, role:shop-dev
    g, acme:shop-release-managers, role:shop-release
    g, acme:platform-admins, role:admin
yaml
# Argo CD Notifications: a Slack service, one template and two triggers from the catalog.
# Applications subscribe with annotations such as
#   notifications.argoproj.io/subscribe.on-sync-failed.slack: shop-deploys
apiVersion: v1
kind: ConfigMap
metadata:
  name: argocd-notifications-cm
  namespace: argocd
data:
  service.slack: |
    token: $slack-token
  context: |
    argocdUrl: https://argocd.acme.internal
  template.app-sync-failed: |
    message: |
      {{.app.metadata.name}} failed to sync revision {{.app.status.operationState.syncResult.revision}}:
      {{.app.status.operationState.message}}
      {{.context.argocdUrl}}/applications/{{.app.metadata.name}}
  template.app-health-degraded: |
    message: |
      {{.app.metadata.name}} is {{.app.status.health.status}}.
      {{.context.argocdUrl}}/applications/{{.app.metadata.name}}
  trigger.on-sync-failed: |
    - when: app.status?.operationState.phase in ['Error', 'Failed']
      send: [app-sync-failed]
  trigger.on-health-degraded: |
    - when: app.status.health.status == 'Degraded'
      send: [app-health-degraded]
yaml
# argocd-cm (excerpt): the knobs this chapter discusses.
apiVersion: v1
kind: ConfigMap
metadata:
  name: argocd-cm
  namespace: argocd
data:
  url: https://argocd.acme.internal
  # poll Git every 120s plus up to 60s jitter (the defaults); webhooks make it instant
  timeout.reconciliation: 120s
  timeout.reconciliation.jitter: 60s
  # annotation tracking (the default in Argo CD 3.x): argocd.argoproj.io/tracking-id
  application.resourceTrackingMethod: annotation
  # SSO through an existing OIDC provider (the bundled Dex is the other option)
  oidc.config: |
    name: Acme SSO
    issuer: https://sso.acme.internal/realms/acme
    clientID: argocd
    clientSecret: $oidc.acme.clientSecret
    requestedScopes: ["openid", "profile", "email", "groups"]
  # disable the built-in admin user once SSO works
  admin.enabled: "false"

Argo CD Image Updater مهم ​

به زبان ساده: Controller جدا، مخزن تصویر (Registry) را پایش می‌کند؛ با پیداشدن Tag جدیدترِ مجاز به Argo CD می‌گوید آن را مصرف کند. حالت مطلوب این است که Tag را در Git ثبت کند.

بدفهمی رایج: «Image Updater پیش‌فرض در Git می‌نویسد.» روش پیش‌فرض نوشتن نتیجه (Write-back)، argocd است که "directly modifies the Argo CD Application resource" و "is pseudo-persistent. If you delete the Application resource from the cluster and re-create it, changes made by Image Updater will be gone." برای GitOps روش git را انتخاب کنید.

تعریف: Argo CD Image Updater، "can check for new versions of the container images that are deployed with your Kubernetes workloads and automatically update them to their latest allowed version using Argo CD". از v1.0.0 با منبع سفارشی ImageUpdater در argocd-image-updater.argoproj.io/v1alpha1 تنظیم می‌شود: applicationRefs[].namePattern، images[].imageName همراه محدودیت نسخه، commonUpdateSettings.updateStrategy با semver، newest-build که نام جدید latest است، alphabetical، digest و calver؛ manifestTargets.kustomize.name یا .helm.name؛ و writeBackConfig.method با argocd یا git و اعتبارنامهٔ git:secret:<ns>/<name>. تنظیم Git شامل gitConfig.branch و gitConfig.writeBackTarget است؛ پیش‌فرض .argocd-source-<appName>.yaml، مقدار kustomization با رفتار "as though you ran kustomize edit set image" و مقدار helmvalues:<path>. محدودیت طراحی: فقط برنامهٔ تحت مدیریت Argo CD و فقط رندرشده با Kustomize، Helm یا Config management plugin.

text
orders-api 1.5.1 pushed to ghcr.io
1  Image Updater reconcile: list tags of ghcr.io/acme/orders-api, constraint 1.x, strategy semver -> 1.5.1
2  app orders-api-staging currently renders 1.5.0 -> update needed
3  git write-back: clone shop-config, checkout main, edit apps/orders-api/overlays/staging/kustomization.yaml
4  commit + push (as the configured Git user)
5  Argo CD sees the new commit -> automated sync -> staging runs 1.5.1

سناریوهای واقعی:

  • Staging همیشه جدیدترین Build از 1.x را بدون دخالت انسان اجرا می‌کند؛ Prod با PR ارتقا می‌یابد.
  • تیم برای Cluster توسعه روی Tagهای main-* از newest-build و برای بقیه از semver استفاده می‌کند.
  • دنبال‌کردن HEAD یا Tag در Application، Git write-back را خراب می‌کند مگر gitConfig.branch تنظیم شود: "your application really should track a branch".
نیازImage UpdaterImage automation در Flux
نصبپروژه و Controller جدا--components-extra=image-reflector-controller,image-automation-controller
پیکربندیImageUpdater CRImageRepository + ImagePolicy + ImageUpdateAutomation
مقصد Tagپارامتر Application، .argocd-source-<app>.yaml، Kustomization یا Helm valuesهر فیلد YAML با نشانگر $imagepolicy
جریان PRgitConfig.branch: "base:target" روی شاخهٔ دیگر می‌نویسدgit.push.branch متفاوت از شاخهٔ Checkout

راه‌حل:

yaml
# Argo CD Image Updater (v1.x, CRD-based): watch the registry for new orders-api tags
# within 1.x and commit the newest one to the staging overlay's kustomization.yaml.
# The git write-back method makes the change persistent; the default "argocd" method
# only patches the Application object in the cluster.
apiVersion: argocd-image-updater.argoproj.io/v1alpha1
kind: ImageUpdater
metadata:
  name: orders-api-staging
  namespace: argocd
spec:
  writeBackConfig:
    method: "git:secret:argocd/git-creds"
    gitConfig:
      branch: main
      writeBackTarget: "kustomization"
  applicationRefs:
    - namePattern: "orders-api-staging"
      images:
        - alias: "orders-api"
          imageName: "ghcr.io/acme/orders-api:1.x"
          commonUpdateSettings:
            updateStrategy: "semver"
          manifestTargets:
            kustomize:
              name: "ghcr.io/acme/orders-api"

کنترل‌گرهای Flux: source-controller، kustomize-controller، helm-controller، notification-controller، image-reflector-controller و image-automation-controller حیاتی ​

به زبان ساده: Flux مجموعه‌ای از Controllerهای کوچک است: یکی دریافت می‌کند، دو تا Apply می‌کنند، یکی رویداد می‌فرستد و می‌گیرد و دو تا به‌روزرسانی Image را خودکار می‌کنند.

بدفهمی رایج: «نصب Flux، Image automation هم می‌دهد.» کنترل‌گرهای تصویر "are not installed by default"؛ با --components-extra اضافه‌شان کنید.

تعریف: نقش source-controller این است: "main role ... is to provide a common interface for artifacts acquisition"؛ احراز هویت، شناسایی تغییر با "semver"، بسته‌بندی tar.gz، آدرس‌پذیر و در دسترس کردن Artifact در Cluster و خبرکردن مصرف‌کننده‌ها. kustomize-controller وضعیت Cluster را از منابع آشتی‌دهی می‌کند: "Generates manifests with Kustomize"، "Decrypts Kubernetes secrets with Mozilla SOPS and KMS"، "Impersonates service accounts (multi-tenancy RBAC)"، "Runs pipelines in a specific order (depends-on relationship)" و "Prunes objects removed from source (garbage collection)". helm-controller اشیای HelmRelease را به عملیات واقعی Helm، "including Helm tests, rollbacks and uninstalls"، همراه اصلاح خودکار خطا (Remediation) تبدیل می‌کند. notification-controller مسئول "inbound and outbound events" است؛ ورودی Webhook از GitHub، GitLab، Harbor و دیگران و خروجی رویداد به Slack، Teams، Discord و دیگران. image-reflector-controller، "scans image repositories and reflects the image metadata"؛ image-automation-controller، "updates YAML files based on the latest images scanned, and commits". مجموع آن‌ها GitOps Toolkit است.

Git config repoor OCI artifactImage registryghcr.io/acme/shop-appsource-controllerGitRepository, OCIRepositorykustomize-controllerKustomization: build, applyhelm-controllerHelmRelease: install/upgradeclusterobjectsnotification-controllerReceiver in, Alert/Provider outfetchwebhook: reconcile nowImage automation (extra components)image-reflector-controllerImageRepository: list tagsImagePolicysemver 2.x: 2.9.0image-automation-controllerrewrite $imagepolicymarkers, commit, pushscanwrite back to Git: staging branch main, prod branch for a PR
text
flux bootstrap github ... --path=clusters/staging (expected, not run)
1  install controllers into flux-system (gotk-components.yaml)
2  create GitRepository flux-system (this repo) + Kustomization flux-system (path clusters/staging)
3  push gotk-components.yaml and gotk-sync.yaml to the repo
4  from now on: source-controller fetches clusters/staging, kustomize-controller applies it,
   including infrastructure.yaml and apps.yaml, which define further Kustomizations

سناریوهای واقعی:

  • ارتقای Flux یک Commit برای تغییر gotk-components.yaml است؛ Flux خودش را ارتقا می‌دهد: "Flux can manage itself just as it manages other resources".
  • kubectl get fluxcd -A تمام اشیای Flux را در همهٔ CRDها فهرست می‌کند.
  • تیم بی‌نیاز از Image automation اصلاً دو Controller تصویر را اجرا نمی‌کند.
ControllerCRDهانصب پیش‌فرض
source-controllerGitRepository، OCIRepository، HelmRepository، HelmChart، Bucketبله
kustomize-controllerKustomizationبله
helm-controllerHelmReleaseبله
notification-controllerProvider، Alert، Receiverبله
image-reflector-controllerImageRepository، ImagePolicyخیر؛ --components-extra
image-automation-controllerImageUpdateAutomationخیر؛ --components-extra
source-watcherArtifactGeneratorخیر؛ --components-extra

راه‌حل: هر Cluster را یک‌بار با مؤلفه‌های لازم Bootstrap کنید؛ پس از آن همهٔ کارها از Git انجام می‌شود.

منابع Flux: GitRepository، OCIRepository و OCI artifacts حیاتی ​

به زبان ساده: شیء منبع (Source) می‌گوید از کجا، هر چند وقت و کدام نسخه دریافت شود؛ خروجی‌اش مصنوع (Artifact) مورد مصرف Controllerهای دیگر است.

بدفهمی رایج: «مخزن تصویر (Registry) در OCI فقط برای Image است.» flux push artifact، "creates a tarball from the given directory or the single file and uploads the artifact to an OCI repository". یک OCIRepository آن را مانند Git دریافت می‌کند و می‌تواند امضای cosign را بررسی کند.

تعریف: "Sources produce an artifact that is consumed by other Flux components" و "The origin of the source is checked for changes on a defined interval". GitRepository شامل url، ref برای branch، tag، semver یا commit، interval و secretRef است. OCIRepository، url: oci://...، ref با tag، semver یا digest، layerSelector و verify با provider: cosign دارد؛ کلید عمومی یا حالت بدون کلید (Keyless) با matchOIDCIdentity و Regexهای issuer و subject را می‌پذیرد. موفقیت، شرط SourceVerified را True می‌کند. در مدل "Gitless GitOps" در Flux، "the Git server is no longer a production dependency, while the OCI registry becomes the unified source of truth for all configuration artifacts". Argo CD هم "supports using OCI (Open Container Initiative) images as an application source" با repoURL: oci://....

text
Config as a signed OCI artifact (prod cluster)
1  merge to main -> CI: flux push artifact oci://ghcr.io/acme/shop-config:<sha> --path=. --source=... --revision=main@sha1:<sha>
2  CI: cosign sign --yes ghcr.io/acme/shop-config@sha256:...   (keyless, workflow OIDC identity)
3  CI: flux tag artifact ...:<sha> --tag prod   (overlays/prod itself only changes by reviewed PR)
4  prod OCIRepository (ref.tag prod) sees a new digest -> verify signature -> SourceVerified=True
5  Kustomization shop-laravel-prod applies ./apps/shop-laravel/overlays/prod from that artifact

سناریوهای واقعی:

  • Clusterهای Prod در شبکهٔ محدود به Mirror مربوط به Registry دسترسی دارند ولی به GitHub نه.
  • سیاست زنجیرهٔ تأمین اجازه می‌دهد فقط Config امضاشده توسط Workflowِ CI در Config repo مستقر شود.
  • Chart از oci://ghcr.io/acme/charts/orders-api با ref.semver: "1.3.x" دریافت می‌شود.
منبعکاربردبررسی اصالت
GitRepositoryConfig repo و repo مستاجرهاامضای Commit با PGP از طریق verify
OCIRepositoryConfig artifact و Chart در OCIcosign با کلید یا Keyless؛ notation
HelmRepositoryrepo کلاسیک Helm روی HTTPمنشأ (Provenance) Chart در Workflow آن
BucketStorage سازگار با S3فقط کنترل دسترسی

راه‌حل:

yaml
# Prod pulls the config as a signed OCI artifact instead of cloning Git ("Gitless"
# GitOps): the config repo's CI runs "flux push artifact" for each commit merged to main,
# signs it and moves the "prod" tag. Prod overlays change only through reviewed PRs.
# Git stays the interface for humans; the registry becomes the production dependency.
# (The staging cluster in this repository reads Git directly.)
apiVersion: source.toolkit.fluxcd.io/v1
kind: OCIRepository
metadata:
  name: shop-config
  namespace: flux-system
spec:
  interval: 5m
  url: oci://ghcr.io/acme/shop-config
  ref:
    tag: prod
  # refuse artifacts that the config repo's CI workflow did not sign (keyless cosign)
  verify:
    provider: cosign
    matchOIDCIdentity:
      - issuer: "^https://token.actions.githubusercontent.com$"
        subject: "^https://github.com/acme/shop-config.*$"
---
# The orders-api Helm chart, published by the service's own CI (see the Helm chapter)
apiVersion: source.toolkit.fluxcd.io/v1
kind: OCIRepository
metadata:
  name: orders-api-chart
  namespace: flux-system
spec:
  interval: 10m
  url: oci://ghcr.io/acme/charts/orders-api
  ref:
    semver: "1.3.x"

Kustomization در Flux: path، prune، interval، dependsOn، health checks و wait حیاتی ​

به زبان ساده: Kustomization در Flux می‌گوید «این پوشه از آن منبع را Apply کن، حذف‌شده‌ها را پاک کن، سلامت را بسنج و هر چند دقیقه دوباره تکرار کن».

بدفهمی رایج: «Kustomization در Flux همان فایل kustomization.yaml است.» دو چیز با یک نام‌اند: Kustomization در kustomize.toolkit.fluxcd.io/v1 یک CRD داخل Cluster است؛ Kustomization در kustomize.config.k8s.io/v1beta1 فایلی است که Kustomize می‌سازد. شیء Flux، "represents a local set of Kubernetes resources (e.g. kustomize overlay) that Flux is supposed to reconcile".

تعریف: فیلدهای اصلی: interval اجباری برای Reconciliation با "correcting any existing drift in the process"؛ retryInterval؛ path؛ prune که "a required boolean field to enable/disable garbage collection" است؛ sourceRef؛ targetNamespace که درباره‌اش kustomize-controller، "will not create the namespace automatically"؛ suspend که "drift detection/correction is paused"؛ healthChecks؛ wait با رفتار "perform health checks for all reconciled resources ... If set to true, .spec.healthChecks is ignored"؛ timeout؛ dependsOn با شرط "only applied after the referred Kustomizations are ready"؛ serviceAccountName؛ decryption برای SOPS؛ postBuild.substitute و force. Annotation هر شیء: kustomize.toolkit.fluxcd.io/ssa با Override، Merge، IfNotPresent و Ignore؛ .../force؛ .../prune: disabled؛ .../reconcile: disabled. مثال مستندات: "every ten minutes, the Kustomization runs a server-side apply dry-run to detect and correct drift inside the cluster."

text
Reconcile of shop-laravel-staging (interval 10m, wait: true, dependsOn infrastructure)
1  infrastructure Ready? no -> requeue (reason DependencyNotReady); yes -> continue
2  fetch artifact of GitRepository flux-system at main@sha1:9a1b...
3  kustomize build ./apps/shop-laravel/overlays/staging; decrypt SOPS Secrets
4  server-side apply dry-run -> changed objects -> apply; Jobs recreated (force: enabled)
5  prune objects from the previous inventory that are gone from this revision
6  wait: all Deployments rolled out, Jobs complete -> Ready=True "Applied revision: main@sha1:9a1b..."
   failure -> Ready=False (BuildFailed / HealthCheckFailed / ...) -> Alert -> Slack

سناریوهای واقعی:

  • CRDها و Controllerها در Kustomization با نام infrastructure هستند و برنامه‌ها به آن dependsOn دارند.
  • غلط املایی در path با kustomization path not found: stat /tmp/kustomization-.../invalid: no such file or directory و دلیل ArtifactFailed شکست می‌خورد؛ این پیام مستندات است.
  • هنگام رخداد، flux suspend kustomization shop-laravel-prod اصلاح Drift را متوقف می‌کند تا مهندس وضعیت زنده را عیب‌یابی کند.
فیلدمقدار این فصلدلیل
intervalبرنامه‌ها 10m، زیرساخت 1hآهنگ اصلاح Drift؛ Webhook برای سرعت
retryInterval1m-2mتلاش سریع‌تر پس از شکست
prunetrueجمع‌آوری اشیای حذف‌شده
waittrue برای shop-laravelReady یعنی Rollout و Jobها کامل شده‌اند
healthChecksDeployment orders-apiفهرست صریح وقتی wait بیش‌ازحد گسترده است
dependsOninfrastructureNamespace پیش از برنامه
decryptionsops / sops-ageSecret رمز‌شده در Git
timeout5m-10mسقف زمان Build، Apply و Health check

راه‌حل: Kustomization برنامهٔ Laravel و سرویس Go:

yaml
# Layer 2: the applications, applied only after "infrastructure" is Ready (dependsOn).
# Every 10 minutes kustomize-controller re-applies the overlay with a server-side
# dry-run diff, so a kubectl edit in shop-staging is reverted at the latest then.
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: orders-api-staging
  namespace: flux-system
spec:
  dependsOn:
    - name: infrastructure
  interval: 10m
  retryInterval: 1m
  timeout: 5m
  path: ./apps/orders-api/overlays/staging
  prune: true
  sourceRef:
    kind: GitRepository
    name: flux-system
  healthChecks:
    - apiVersion: apps/v1
      kind: Deployment
      name: orders-api
      namespace: shop-staging
---
# The Laravel app. wait: true health-checks every object it applied, including the
# migrate and smoke Jobs. Flux has no hook phases: both Jobs start in the same reconcile
# as the new Deployments. The smoke command polls the web Service until it serves the new
# version before checking anything else, so Ready=True means applied, rolled out, migrated
# and smoke-tested against the new pods.
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: shop-laravel-staging
  namespace: flux-system
spec:
  dependsOn:
    - name: infrastructure
  interval: 10m
  retryInterval: 1m
  timeout: 10m
  path: ./apps/shop-laravel/overlays/staging
  prune: true
  wait: true
  sourceRef:
    kind: GitRepository
    name: flux-system
  # the env Secret is committed encrypted with SOPS (age); the controller decrypts it
  decryption:
    provider: sops
    secretRef:
      name: sops-age
yaml
# Layer 1: cluster-wide objects (namespaces here; CRDs and controllers in real life).
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: infrastructure
  namespace: flux-system
spec:
  interval: 1h
  retryInterval: 1m
  timeout: 5m
  path: ./infrastructure/namespaces
  prune: true
  wait: true
  sourceRef:
    kind: GitRepository
    name: flux-system
yaml
# The Laravel app in prod from the OCI artifact. Same overlay path, different source.
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: shop-laravel-prod
  namespace: flux-system
spec:
  dependsOn:
    - name: infrastructure
  interval: 10m
  retryInterval: 2m
  timeout: 10m
  path: ./apps/shop-laravel/overlays/prod
  prune: true
  wait: true
  sourceRef:
    kind: OCIRepository
    name: shop-config
  decryption:
    provider: sops
    secretRef:
      name: sops-age

HelmRelease: انتشار واقعی Helm، Remediation و تشخیص Drift مهم ​

به زبان ساده: HelmRelease یعنی «این Chart با این نسخه و این Values نصب بماند»؛ Controller آن را با اجرای واقعی helm install/upgrade عملی می‌کند.

بدفهمی رایج: «Argo CD و Flux با Helm یکسان رفتار می‌کنند.» Argo CD، Chart را رندر و خودش خروجی را Apply می‌کند؛ انتشار در helm list نیست. helm-controller عملیات Helm را اجرا می‌کند؛ رفتار Hook، Test، تاریخچهٔ انتشار و helm rollback همان Helm است.

تعریف: chartRef به OCIRepository یا HelmChart اشاره دارد: "One of .spec.chart or .spec.chartRef must be set, but not both". دیگر فیلدها releaseName، values / valuesFrom، install.remediation.retries، upgrade.remediation.retries، test.enable و driftDetection هستند. رفتار تشخیص Drift: "When .spec.driftDetection.mode is set to warn or enabled ... the controller will compare the manifest from the Helm storage with the current state of the cluster using a server-side dry-run apply". با enabled، "will attempt to correct the drift". فیلد ignore، JSON pointer می‌گیرد و "useful when Horizontal Pod Autoscaling is enabled" است.

text
HelmRelease orders-api upgrade 1.4.2 -> 1.5.0 fails
1  helm-controller: upgrade -> pods never Ready -> timeout 5m -> upgrade failed
2  remediation retries 3: retry ... still failing -> RetriesExceeded
3  upgrade.remediation.strategy: rollback ("Defaults to rollback"; uninstall is the other value) restores the last release
4  Ready=False with the failure reason -> Alert -> Slack; Git still says 1.5.0 -> revert the commit

سناریوهای واقعی:

  • Chartهای بیرونی مانند ingress-nginx و cert-manager به‌شکل HelmRelease با Values در Git.
  • تشخیص Drift، حذف دستی NetworkPolicy مربوط به Chart را پیدا می‌کند.
  • Chart سرویس Go در بسته‌بندی Kubernetes به Prod تحویل می‌شود.
موضوعHelmRelease در FluxArgo CD با منبع Helm
نمایش در helm listبلهخیر
Helm hooksHook واقعی Helmنگاشت به Hookهای Argo CD
Upgrade ناموفقRemediation: تلاش مجدد، Rollback، UninstallSync ناموفق؛ سیاست Retry
DriftdriftDetection.mode با warn / enabledselfHeal

راه‌حل:

yaml
# The Go service in prod as a HelmRelease: helm-controller runs a real Helm upgrade
# (the release shows in "helm list"), retries and rolls back on failure, and with
# driftDetection.mode=enabled corrects in-cluster edits against the stored release.
apiVersion: helm.toolkit.fluxcd.io/v2
kind: HelmRelease
metadata:
  name: orders-api
  namespace: shop-prod
spec:
  interval: 15m
  timeout: 5m
  releaseName: orders-api
  chartRef:
    kind: OCIRepository
    name: orders-api-chart
    namespace: flux-system
  install:
    remediation:
      retries: 3
  upgrade:
    remediation:
      retries: 3
  driftDetection:
    mode: enabled
    ignore:
      # the HPA owns the replica count
      - paths: ["/spec/replicas"]
        target:
          kind: Deployment
  values:
    image:
      repository: ghcr.io/acme/orders-api
      # the promote-to-prod workflow bumps tag and digest here in the same PR as
      # apps/orders-api/overlays/prod (tag for humans, digest for the exact bytes)
      tag: "1.4.2"
      digest: sha256:0b7e2a3c5d9f41e6a8b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3

اعلان‌های Flux: Receiver، Alert و Provider مهم ​

به زبان ساده: Receiver به GitHub اجازه می‌دهد همان لحظهٔ Push، Flux را خبر کند؛ Alert همراه Provider رویداد Flux را به Slack می‌فرستد یا وضعیت Commit را تنظیم می‌کند.

بدفهمی رایج: «Flux بدون Webhook ذاتاً کند است.» Polling پشتیبان است؛ Receiver تحویل را تقریباً فوری می‌کند و گم‌شدن Webhook فقط یک بازه تأخیر می‌دهد.

تعریف: Receiver با type: github، gitlab، generic، harbor و غیره، events، secretRef برای Token مشترک و resources برای Reconciliation تعریف می‌شود. Service با نام webhook-receiver آن را در مسیر منتشرشده در .status.webhookPath یعنی /hook/<sha256> ارائه می‌کند. Provider مقصد است: type: slack با channel، address و secretRef؛ type: github برای "Git Commit Status Updates"؛ githubdispatch و بسیاری دیگر. Alert، eventSources شامل kind، name و namespace، eventSeverity با info یا error را انتخاب و eventMetadata را اضافه می‌کند.

text
git push -> GitHub webhook -> https://flux-webhook.acme.internal/hook/bed6d0...
1  notification-controller validates the token, matches Receiver github-shop-config
2  annotates GitRepository flux-system to reconcile now -> source-controller fetches
3  Kustomizations depending on it reconcile -> events (info/error)
4  Alert shop-errors (severity error) -> Provider slack -> #shop-deploys
5  Alert shop-commit-status -> Provider github -> commit status on the config repo

سناریوهای واقعی:

  • تأخیر استقرار از حداکثر ده دقیقه به چند ثانیه می‌رسد.
  • صفحهٔ Commit در Config repo نشان می‌دهد آیا Staging آن Commit را آشتی‌دهی کرده است.
  • Harbor رویداد Push را به Receiver می‌فرستد تا ImageRepository آشتی‌دهی شود.
شیءجهتفیلدهای اصلی
Receiverورودی؛ Webhooktype، events، secretRef، resources
Providerخروجی؛ مقصدtype، address، channel، secretRef
Alertخروجی؛ مسیریابیproviderRef، eventSources، eventSeverity، eventMetadata

راه‌حل:

yaml
# Outbound: errors from any Kustomization or HelmRelease go to Slack.
apiVersion: notification.toolkit.fluxcd.io/v1
kind: Provider
metadata:
  name: slack
  namespace: flux-system
spec:
  type: slack
  channel: shop-deploys
  address: https://slack.com/api/chat.postMessage
  secretRef:
    name: slack-bot-token
---
apiVersion: notification.toolkit.fluxcd.io/v1
kind: Alert
metadata:
  name: shop-errors
  namespace: flux-system
spec:
  providerRef:
    name: slack
  eventSeverity: error
  eventMetadata:
    env: staging
  eventSources:
    - kind: Kustomization
      name: '*'
    - kind: HelmRelease
      name: '*'
---
# Outbound: commit statuses on the config repo (the commit shows whether it reconciled)
apiVersion: notification.toolkit.fluxcd.io/v1
kind: Provider
metadata:
  name: github-status
  namespace: flux-system
spec:
  type: github
  address: https://github.com/acme/shop-config
  secretRef:
    name: github-status-token
---
apiVersion: notification.toolkit.fluxcd.io/v1
kind: Alert
metadata:
  name: shop-commit-status
  namespace: flux-system
spec:
  providerRef:
    name: github-status
  eventSeverity: info
  eventSources:
    - kind: Kustomization
      name: shop-laravel-staging
---
# Inbound: GitHub push webhooks trigger an immediate fetch instead of waiting for
# the next interval. The URL path is published in .status.webhookPath (/hook/<sha256>).
apiVersion: notification.toolkit.fluxcd.io/v1
kind: Receiver
metadata:
  name: github-shop-config
  namespace: flux-system
spec:
  type: github
  events:
    - "ping"
    - "push"
  secretRef:
    name: receiver-token
  resources:
    - apiVersion: source.toolkit.fluxcd.io/v1
      kind: GitRepository
      name: flux-system

خودکارسازی تصویر در Flux: ImageRepository، ImagePolicy، ImageUpdateAutomation و نوشتن در Git حیاتی ​

به زبان ساده: Flux، مخزن تصویر (Registry) را اسکن می‌کند، جدیدترین Tag مجاز سیاست شما را برمی‌گزیند، خط‌های نشان‌دار Git را ویرایش و Commit می‌کند. سپس حلقهٔ معمول GitOps همان Commit را مستقر می‌کند.

بدفهمی رایج: «Image automation، Deployment داخل Cluster را به‌روز می‌کند.» مستقیماً به Cluster دست نمی‌زند؛ در Git می‌نویسد. Cluster فقط در پی تغییر Git عوض می‌شود و سابقهٔ ممیزی کامل می‌ماند.

تعریف: ImageRepository با image، interval و secretRef از image-reflector-controller می‌خواهد Tagها را فهرست کند. ImagePolicy با imageRepositoryRef، policy.semver.range / numerical / alphabetical، filterTags.pattern و extract و digestReflectionPolicy یکی را انتخاب می‌کند. پیش‌انتشار به بازه‌ای مانند ^1.x-0 نیاز دارد. ImageUpdateAutomation با sourceRef، git.checkout.ref.branch، git.commit.author و messageTemplate، git.push.branch، update.path و update.strategy: Setters فیلدهای دارای # {"$imagepolicy": "<policy-namespace>:<policy-name>"} را بازنویسی می‌کند؛ این نشانگر ارجاع کامل است و پسوندهای :tag، :name و :digest هم مجازند. اگر push.branch با شاخهٔ Checkout فرق کند، "If the specified branch doesn't exist, Flux will create it for you"؛ این پایهٔ جریان متکی به تأیید PR است.

text
image automation of the Laravel tag, staging
1  CI pushes ghcr.io/acme/shop-app:2.9.0 (and sha-4f2a9c1)
2  ImageRepository shop-app scan: tags [2.7.0 2.8.1 2.9.0 sha-4f2a9c1 ...]  (CI pushed shop-web:2.9.0 first)
3  ImagePolicy shop-laravel: filterTags ^[0-9]+\.[0-9]+\.[0-9]+$, semver >=2.0.0 <3.0.0 -> 2.9.0
4  ImageUpdateAutomation shop-laravel-staging: checkout main, path overlays/staging,
   both lines newTag: "2.8.1" # {"$imagepolicy": "flux-system:shop-laravel:tag"}  ->  "2.9.0"
   (shop-app and shop-web carry the SAME marker, so they change in the same commit)
5  commit "chore(staging): update shop-laravel images" by fluxcdbot, push main
6  Kustomization shop-laravel-staging: new revision -> apply Deployments + migrate and smoke Jobs together;
   the smoke command polls shop-web /version until it serves 2.9.0, then checks DB, schema, cache
   prod automation: same edit pushed to image-updates/shop-prod -> PR -> review -> merge -> prod

سناریوهای واقعی:

  • Staging هر انتشار را خودکار دنبال می‌کند؛ Prod برای هر انتشار PR می‌گیرد.
  • CI، Tagهای sha-<commit> هم Push می‌کند؛ filterTags آن‌ها را از سیاست semver کنار می‌گذارد.
  • غلط در نام سیاست یک نشانگر یعنی آن فیلد هرگز به‌روز نمی‌شود؛ تست‌های Repository در این فصل PR را رد می‌کنند.
  • دو Image که باید با هم جابه‌جا شوند، یعنی php-fpm با نام shop-app و Nginx با نام shop-web، یک ImagePolicy و نشانگر یکسان در هر دو خط می‌گیرند. دو سیاست مستقل ممکن است برای یکی 2.9.0 و برای دیگری هنوز 2.8.1 انتخاب کنند؛ تست imagebump دقیقاً این وضعیت را مدل می‌کند و تغییر هر دو خط را اطمینان‌سنجی می‌کند.
شیءControllerپاسخ به کدام پرسش
ImageRepositoryimage-reflector-controllerچه Tagهایی موجود است؟
ImagePolicyimage-reflector-controllerجدیدترین Tag مجاز کدام است؟
ImageUpdateAutomationimage-automation-controllerکدام فایل، کدام شاخه و چه پیام Commit؟
نشانگر $imagepolicyداخل YAML شماکدام فیلد چه مقداری بگیرد؟

راه‌حل: سیاست‌ها و دو Automation در ادامه‌اند؛ نشانگرها داخل Overlay هستند:

yaml
# Image automation for the Laravel images (installed with
# --components-extra=image-reflector-controller,image-automation-controller).
# 1. ImageRepository: image-reflector-controller lists the tags in the registry.
# 2. ImagePolicy: picks the newest tag inside the semver range.
# 3. ImageUpdateAutomation: image-automation-controller rewrites the marked fields
#    in Git and pushes a commit; the Kustomization above then deploys it.
# One ImageRepository and ONE ImagePolicy for both Laravel images: CI releases shop-app
# and shop-web with the same version tag and pushes shop-web first, so a tag that exists
# for shop-app exists for shop-web. Both overlay lines carry the same marker and change
# in one commit; two independent policies could leave app 2.9.0 next to web 2.8.1.
apiVersion: image.toolkit.fluxcd.io/v1
kind: ImageRepository
metadata:
  name: shop-app
  namespace: flux-system
spec:
  image: ghcr.io/acme/shop-app
  interval: 5m
  secretRef:
    name: ghcr-read
---
apiVersion: image.toolkit.fluxcd.io/v1
kind: ImagePolicy
metadata:
  name: shop-laravel
  namespace: flux-system
spec:
  imageRepositoryRef:
    name: shop-app
  # only release tags like 2.8.1 (CI also pushes sha-<commit> tags, which are ignored)
  filterTags:
    pattern: '^[0-9]+\.[0-9]+\.[0-9]+$'
  policy:
    semver:
      range: '>=2.0.0 <3.0.0'
---
# staging: commit straight to main
apiVersion: image.toolkit.fluxcd.io/v1
kind: ImageUpdateAutomation
metadata:
  name: shop-laravel-staging
  namespace: flux-system
spec:
  interval: 10m
  sourceRef:
    kind: GitRepository
    name: flux-system
  git:
    checkout:
      ref:
        branch: main
    commit:
      author:
        name: fluxcdbot
        email: fluxcdbot@users.noreply.github.com
      messageTemplate: |-
        chore(staging): update shop-laravel images

        {{ .Changed.Summary }}
    push:
      branch: main
  update:
    path: ./apps/shop-laravel/overlays/staging
    strategy: Setters
---
# prod: same policies, but push to a separate branch; a pull request from
# image-updates/shop-prod to main is the human approval step
apiVersion: image.toolkit.fluxcd.io/v1
kind: ImageUpdateAutomation
metadata:
  name: shop-laravel-prod
  namespace: flux-system
spec:
  interval: 30m
  sourceRef:
    kind: GitRepository
    name: flux-system
  git:
    checkout:
      ref:
        branch: main
    commit:
      author:
        name: fluxcdbot
        email: fluxcdbot@users.noreply.github.com
      messageTemplate: |-
        chore(prod): promote shop-laravel images

        {{ .Changed.Summary }}
    push:
      branch: image-updates/shop-prod
  update:
    path: ./apps/shop-laravel/overlays/prod
    strategy: Setters
yaml
# staging: Flux image automation owns the two tags below. Both carry the marker of the
# single shop-laravel ImagePolicy, so image-automation-controller rewrites them together
# in one commit to main.
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: shop-staging
resources:
  - ../../base
  - ../../release-jobs
labels:
  - pairs:
      app.kubernetes.io/environment: staging
images:
  - name: ghcr.io/acme/shop-app
    newTag: "2.8.1" # {"$imagepolicy": "flux-system:shop-laravel:tag"}
  - name: ghcr.io/acme/shop-web
    newTag: "2.8.1" # {"$imagepolicy": "flux-system:shop-laravel:tag"}
replicas:
  - name: shop-web
    count: 1
  - name: shop-worker
    count: 1

آماده‌سازی با flux bootstrap و چندمستاجری (Multi-tenancy) مهم ​

به زبان ساده: Bootstrap، Flux را نصب و Manifestهای خود Flux را در repo ثبت می‌کند تا خودش را مدیریت کند. چندمستاجری (Multi-tenancy) باعث می‌شود اشیای Flux هر تیم فقط با مجوز همان تیم اجرا شوند.

بدفهمی رایج: «Flux همه‌چیز را با cluster-admin اعمال می‌کند، پس مستاجر هر کاری می‌تواند بکند.» پیش‌فرض ServiceAccount خود Controller استفاده می‌شود؛ با Flagهای محدودسازی، Kustomization مستاجر بدون serviceAccountName به حساب default همان Namespace برمی‌گردد و نمی‌تواند Namespace دیگری را تغییر دهد.

تعریف: flux bootstrap github، "deploys the Flux controllers on a Kubernetes cluster and configures the controllers to sync the cluster state from a GitHub repository"، Manifestهای Flux را Push و "configures Flux to update itself from Git". پس از آن "any operation on the cluster (including Flux upgrades) can be done via Git push". اجراکننده به دسترسی cluster-admin و مدیریت Repository نیاز دارد؛ PAT با --token-auth در Secret با نام flux-system ذخیره می‌شود. در Multi-tenancy مدیر Platform، Bootstrap و افزودن CRD و Controller را انجام می‌دهد، "Set up namespaces for tenants and define their level of access with Kubernetes RBAC" و repo مستاجر را معرفی می‌کند؛ مستاجر منبع ثبت می‌کند و "into their namespace(s)" استقرار می‌دهد. Patchهای محدودسازی شامل --no-cross-namespace-refs=true برای بیشتر Controllerها، --no-remote-bases=true برای kustomize-controller و --default-service-account=default برای kustomize-controller، helm-controller و source-watcher هستند.

text
Tenant team-orders pushes a manifest for namespace payments (expected, not run)
1  Kustomization team-orders (serviceAccountName team-orders-reconciler, targetNamespace team-orders)
2  kustomize-controller impersonates system:serviceaccount:team-orders:team-orders-reconciler
3  apply in team-orders: allowed (RoleBinding to ClusterRole admin, namespaced)
4  targetNamespace rewrites everything into team-orders; a ClusterRole in the tenant repo -> forbidden
5  Ready=False with the API server's forbidden message -> the tenant fixes their repo

سناریوهای واقعی:

  • تیم Platform یک Cluster را برای هشت تیم محصول اداره می‌کند؛ هر تیم repo استقرار خودش را دارد.
  • --no-remote-bases=true جلوی دریافت Manifest بازبینی‌نشده از اینترنت در هر Reconciliation را می‌گیرد.
  • برای تعویض Deploy key، Secret با نام flux-system را حذف و Bootstrap را دوباره اجرا کنید.
Flag یا فیلداثر
--components-extra=image-reflector-controller,image-automation-controllerنصب Image automation
--path=clusters/<name>پوشه‌ای که این Cluster همگام می‌کند
--read-write-keyDeploy key با حق نوشتن؛ لازم برای Image automation
serviceAccountNameاستفاده از هویت مشخص برای هر Kustomization/HelmRelease
--no-cross-namespace-refs=trueمستاجر نمی‌تواند به منبع Namespace دیگر ارجاع دهد
--default-service-account=defaultشیء بدون serviceAccountName هویت محلی Namespace می‌گیرد

راه‌حل:

yaml
# Flux multi-tenancy: the platform team onboards the orders team. Their own repository
# is reconciled under a namespaced ServiceAccount, so a tenant manifest that targets
# another namespace or a cluster-scoped kind is rejected by Kubernetes RBAC.
# (Lockdown flags on the controllers: --no-cross-namespace-refs=true,
#  --default-service-account=default, --no-remote-bases=true.)
apiVersion: v1
kind: Namespace
metadata:
  name: team-orders
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: team-orders-reconciler
  namespace: team-orders
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: team-orders-reconciler
  namespace: team-orders
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  # the built-in "admin" ClusterRole bound by a RoleBinding: admin of this namespace only
  name: admin
subjects:
  - kind: ServiceAccount
    name: team-orders-reconciler
    namespace: team-orders
---
apiVersion: source.toolkit.fluxcd.io/v1
kind: GitRepository
metadata:
  name: team-orders
  namespace: team-orders
spec:
  interval: 5m
  url: https://github.com/acme/team-orders-deploy
  ref:
    branch: main
  secretRef:
    name: team-orders-git
---
apiVersion: kustomize.toolkit.fluxcd.io/v1
kind: Kustomization
metadata:
  name: team-orders
  namespace: team-orders
spec:
  serviceAccountName: team-orders-reconciler
  targetNamespace: team-orders
  interval: 10m
  path: ./deploy
  prune: true
  sourceRef:
    kind: GitRepository
    name: team-orders

تشخیص Drift، خود‌ترمیمی و برگرداندن تغییر دستی حیاتی ​

به زبان ساده: انحراف (Drift) تفاوت Git و Cluster است که کسی Commit نکرده؛ خود‌ترمیمی (Self-heal) یعنی Agent آن را برگرداند. گاهی باید فوری برگردد و گاهی لازم است یک ساعت باقی بماند.

بدفهمی رایج: «Self-heal، kubectl edit را ناممکن می‌کند، پس هنگام رخداد باید خاموش باشد.» اقدام بهتر صریح است: Reconciliation همان برنامه را Suspend کنید؛ در Flux با flux suspend kustomization یا kustomize.toolkit.fluxcd.io/reconcile: disabled روی یک شیء. در Argo CD، Automated sync همان Application را خاموش کنید؛ اگر ApplicationSet آن را ساخته، فقط وقتی پایدار می‌ماند که ApplicationSet برای /spec/syncPolicy، ignoreApplicationDifferences داشته باشد. سپس وضعیت زنده را تغییر دهید، اصلاح را Commit کنید و Resume کنید.

تعریف: تشخیص انحراف (Drift detection) مرحلهٔ مقایسه در هر Reconciliation است. Argo CD، OutOfSync گزارش می‌کند و با selfHeal: true پس از Self-heal timeout دوباره Sync می‌کند. مستندات Flux: "If you make any changes to the cluster using kubectl edit/patch/delete, they will be promptly reverted. You either suspend the reconciliation or push your changes to a Git repository." FAQ می‌افزاید "fields specified in Git will always be overridden"؛ فقط فیلدهای تازه افزوده‌شده با Field manager به نام flux-client-side-apply باقی می‌مانند؛ مانند kubectl --field-manager=flux-client-side-apply rollout restart. HelmRelease فقط با driftDetection.mode: enabled انحراف را اصلاح می‌کند.

text
02:00 incident: orders-api leaking memory; on-call scales it up by hand
1  kubectl scale deploy/orders-api --replicas=12 -n shop-prod
2a Argo CD, selfHeal on, Git sets replicas -> back to the Git value within seconds; on-call confused
2b Flux Kustomization -> back to Git at the next interval (<= 10m)
3  right way: suspend first, act, open PR
     Flux:    flux suspend kustomization orders-api-prod
     Argo CD: set spec.syncPolicy.automated.enabled: false on the Application. For an ApplicationSet-generated
              app, "changing the application's spec.syncPolicy.automated field will, however, have no effect"
              unless the ApplicationSet ignores it: ignoreApplicationDifferences: [{jsonPointers: [/spec/syncPolicy]}]
              (set in appset-shop.yaml); otherwise pause at the ApplicationSet (template or applicationsSync policy)
4  after the fix is merged: resume; the agent and Git agree again

سناریوهای واقعی:

  • توسعه‌دهنده «موقتاً» با kubectl set env مقدار LOG_LEVEL=debug می‌گذارد؛ GitOps قبل از پرشدن دیسک آن را برمی‌گرداند.
  • مهاجم با اعتبارنامهٔ دزدیده‌شده Image یک Deployment را تغییر می‌دهد؛ Self-heal آن را بازمی‌گرداند و رویداد OutOfSync مدرک است.
  • تست بار به Replica ثابت برای یک ساعت نیاز دارد؛ برنامه را Suspend کنید یا تغییر را در Overlay یک شاخه Commit کنید.
زمانSelf-heal یا اصلاح Driftدلیل
Production بدون دسترسی دستیروشنGit تنها مرجع است؛ Drift رخداد است
Cluster مشترک توسعهروشن با مسیر سریع PRجلوگیری از پیکربندی‌های تک‌افتاده
رخداد فعال در برنامهفقط همان برنامه Suspend شودانسان نباید با Agent رقابت کند
فیلد متعلق به Controller مانند HPA یا Meshروشن با قواعد Ignoreوگرنه Agent و Controller مدام هم را خنثی می‌کنند
مهاجرت از استقرار Pushیک هفته خاموش؛ پایش OutOfSyncیافتن تغییر دستی پنهان پیش از برگرداندن آن

راه‌حل: هرجا ممکن است Self-heal را روشن کنید، برای OutOfSync بیش از چند دقیقه هشدار بگذارید و Suspend/Resume را در راهنمای عملیات (Runbook) بنویسید. مدل Drift در Go نشان می‌دهد چرا فیلد پیش‌فرض سرور Drift نیست و چرا Ignore لازم است.

اسرار در GitOps: SOPS، Sealed Secrets و ESO مهم ​

به زبان ساده: هرگز Secret ساده را Commit نکنید. Secret رمز‌شده با SOPS یا Sealed Secrets، یا ارجاع به Secret manager با External Secrets Operator را ثبت کنید.

بدفهمی رایج: «Repository خصوصی به‌اندازهٔ کافی امن است.» Flux می‌گوید: "Storing Secrets in Git repositories in plain text or base64 is unsafe, regardless of the visibility or access restrictions of the repository."

تعریف: سه الگو با جزئیات در پیکربندی، Secrets و Storage در Kubernetes: SOPS، "is an editor of encrypted files that supports YAML, JSON, ENV, INI and BINARY formats and encrypts with AWS KMS, GCP KMS, Azure Key Vault, HuaweiCloud KMS, age, and PGP". kustomize-controller با spec.decryption.provider: sops رمزگشایی می‌کند: "The only supported encryption provider is SOPS". Argo CD مرحلهٔ داخلی SOPS ندارد؛ معمولاً Config management plugin اضافه می‌کنند یا ESO را ترجیح می‌دهند. Sealed Secrets با کلید نزد Controller، SealedSecret را داخل Cluster رمزگشایی می‌کند؛ مستندات Declarative در Argo CD حتی آن را برای اعتبارنامهٔ Repository پیشنهاد می‌کنند. ESO یعنی External Secrets Operator از Vault، AWS Secrets Manager و دیگران Sync می‌کند و Git فقط ExternalSecret دارد. جزئیات و بده‌بستان‌ها در Secrets در GitOps و ESO است.

text
SOPS with Flux (expected, not run)
1  sops --encrypt --age age1... secret.yaml > secret.enc.yaml ; commit secret.enc.yaml
2  kustomize-controller: build overlay, find SOPS-encrypted Secret, decrypt with key from Secret sops-age
3  apply the plain Secret to the cluster; Git only ever saw ciphertext

سناریوهای واقعی: Secret برنامهٔ Laravel با نام shop-laravel-env شامل APP_KEY و رمز DB به‌شکل SOPS در Git برای Flux یا ExternalSecret برای Argo CD؛ اعتبارنامهٔ Registry در secretRef مربوط به ImageRepository؛ Token اعلان Slack در argocd-notifications-secret.

الگوپشتیبانی Agentجای کلید
SOPSداخلی در Flux؛ با Plugin در Argo CDKMS یا کلید age در Cluster
Sealed Secretsهر دو؛ فقط یک CR استکلید Controller در Cluster
External Secrets Operatorهر دو؛ فقط یک CR استSecret manager بیرونی

راه‌حل: برای هر Platform یک روش انتخاب کنید؛ Kustomizationهای Flux این فصل SOPS دارند؛ decryption بالا را ببینید.

ارتقای محیط (Environment promotion): PR تغییر Image tag و Kargo حیاتی ​

به زبان ساده: ارتقا (Promotion) یعنی کپی‌کردن «نسخهٔ موفق در Staging» به وضعیت مطلوب Prod. در GitOps این کار یک Commit است؛ بهتر است با PR بازبینی‌شده انجام شود.

بدفهمی رایج: «Promotion یعنی Merge شاخهٔ Staging به Prod.» با پوشهٔ جدا برای محیط‌ها، Promotion یک Diff کوچک در overlays/prod شامل Tag و Digest است؛ Merge شاخه‌ای نیست که همهٔ تغییرهای دیگر را هم ببرد.

تعریف: ارتقای محیط (Environment promotion) نسخهٔ سالم Artifact را میان Stageها جابه‌جا می‌کند. روش‌های رایج: PR تغییر برچسب تصویر (Image tag bump PR) از CI یا ربات یا Image automation در Flux که به شاخهٔ جدا Push می‌کند؛ Argo CD Image Updater با gitConfig.branch: "base:target"؛ یا Kargo، "an unopinionated continuous promotion platform". مرز کار در مستندات Kargo روشن است: "Promotions are different from deployments ... The job of deploying ... is left to a GitOps agent like Argo CD." اصطلاحات آن: Warehouse برای مشاهدهٔ Repositoryها و بسته‌بندی Revision تازه؛ Freight، "a 'meta-artifact' that references specific revisions of artifacts like images and manifests"؛ Stage، "a promotion target"؛ و Promotion و Project.

App repo CIbuild, test, push:1.5.0 @digestoverlays/stagingbot commit on mainnewTag: 1.5.0staging clustersync, Healthy,PostSync smoke okpromotion PRoverlays/prod: 1.5.0+ digest, review, mergeprod clustersync in an allowedsync windowrollback =git revert thepromotion committagpullpassed: open PR (bot or Kargo)pull
text
orders-api 1.5.0 from staging to prod
1  staging runs 1.5.0 (Image Updater commit), Healthy for 24 h, PostSync smoke ok
2  release manager runs workflow promote-to-prod (app=orders-api, tag=1.5.0, digest=sha256:...)
3  imagebump edits apps/orders-api/overlays/prod/kustomization.yaml (Argo CD's source) AND
   clusters/prod/helmrelease-orders-api.yaml values.image (Flux's source): 2 lines each, one PR
4  PR "promote(prod): orders-api 1.5.0" -> CODEOWNERS review, config-repo checks green -> merge
5  Argo CD (prod) syncs inside the allowed sync window -> Healthy

سناریوهای واقعی:

  • چند Artifact باید با هم حرکت کنند، مثلاً Image و تغییر Config؛ Kargo Freight آن‌ها را بسته‌بندی می‌کند.
  • در Prod مقررات‌محور، تأیید PR همان سابقهٔ تغییر است.
  • Staging هر Patch را می‌گیرد؛ Prod هفته‌ای یک PR با Tag آزموده‌شده دریافت می‌کند.
سازوکارنویسندهٔ Commitدروازه
CI، PR باز می‌کند؛ Workflow این فصلربات CIبازبینی PR
Image automation در Flux به شاخهimage-automation-controllerبازبینی PR
شاخهٔ base:target در Argo CD Image UpdaterImage Updaterبازبینی PR
Kargo PromotionKargo با مراحل Git commit، PR و Argo CD updateاعتبارسنجی Stage، دستی یا خودکار
Commit مستقیم به mainهر دارندهٔ حق Pushندارد؛ برای Prod پرهیز کنید

راه‌حل: Workflow ارتقا و ابزارش در ادامه‌اند. هر فایلی که نسخهٔ Prod را مشخص می‌کند باید در همان PR تغییر کند؛ اگر فقط Overlay تغییر کند، HelmRelease در Flux که values.image خودش را دارد روی نسخهٔ قدیمی می‌ماند:

yaml
# Promotion = a pull request. A release manager runs this workflow with the tag that
# passed staging; it rewrites EVERY file that names the prod version (the prod overlay
# that Argo CD renders and, when the app is also delivered by a Flux HelmRelease, that
# HelmRelease's values.image) and opens one PR. Merging it is the deployment approval.
name: promote-to-prod
on:
  workflow_dispatch:
    inputs:
      app:
        description: "App directory under apps/ (orders-api or shop-laravel)"
        required: true
      image:
        description: "Image repository, e.g. ghcr.io/acme/orders-api"
        required: true
      tag:
        description: "Tag that passed staging, e.g. 1.5.0"
        required: true
      digest:
        description: "Digest CI printed for that tag (sha256:...)"
        required: true
permissions:
  contents: write
  pull-requests: write
jobs:
  open-pr:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-go@v7
        with:
          go-version-file: tools/go.mod
      - name: Bump the prod overlay and the prod HelmRelease
        working-directory: tools
        run: |
          set -euo pipefail
          go run ./cmd/imagebump \
            -file "../apps/${{ inputs.app }}/overlays/prod/kustomization.yaml" \
            -image "${{ inputs.image }}" -tag "${{ inputs.tag }}" -digest "${{ inputs.digest }}"
          hr="../clusters/prod/helmrelease-${{ inputs.app }}.yaml"
          if [ -f "$hr" ]; then
            go run ./cmd/imagebump -format helm -file "$hr" \
              -image "${{ inputs.image }}" -tag "${{ inputs.tag }}" -digest "${{ inputs.digest }}"
          fi
      - name: Open the promotion pull request
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          BRANCH: promote/${{ inputs.app }}-${{ inputs.tag }}
        run: |
          set -euo pipefail
          git config user.name "release-bot"
          git config user.email "release-bot@users.noreply.github.com"
          git switch -c "$BRANCH"
          git commit -am "promote(prod): ${{ inputs.app }} ${{ inputs.tag }}"
          git push origin "$BRANCH"
          gh pr create --base main --head "$BRANCH" \
            --title "promote(prod): ${{ inputs.app }} ${{ inputs.tag }}" \
            --body "Tag ${{ inputs.tag }} (${{ inputs.digest }}) passed staging."

Rollback با Revert در برابر argocd app rollback حیاتی ​

به زبان ساده: Commit خراب‌کننده را Revert کنید. دکمهٔ Rollback در Argo CD وجود دارد، ولی Cluster را با Git ناهماهنگ می‌کند.

بدفهمی رایج: «argocd app rollback همان Rollback در GitOps است.» Revision قدیمی تاریخچهٔ Application را دوباره Sync می‌کند و "Rollback cannot be performed against an application with automated sync enabled". ابتدا Auto-sync باید خاموش شود؛ پس از آن Cluster چیزی اجرا می‌کند که Git نمی‌گوید.

تعریف: بازگشت با Revert (Rollback by revert): فرمان git revert <sha>، Commit تازه‌ای برای برگرداندن وضعیت مطلوب قبلی می‌سازد؛ Agent مثل هر تغییر آن را Sync می‌کند و تاریخچه خطی و قابل ممیزی می‌ماند. argocd app rollback APPNAME [ID]: "Rollback application to a previous deployed version by History ID, omitted will Rollback to the previous version"؛ --prune مجاز است و طول تاریخچه با spec.revisionHistoryLimit تعیین می‌شود. Flux فرمان Rollback ندارد؛ Remediation در helm-controller می‌تواند Upgrade ناموفق Helm را برگرداند، اما تا Revert نکنید Git هنوز نسخهٔ جدید را می‌خواهد.

text
1.5.0 broke prod at 14:02
revert path                                   rollback-button path
1 git revert 3e9d (promotion commit)          1 disable automated sync on orders-api-prod (needs the ignoreApplicationDifferences rule: generated app)
2 PR (fast-track approval) -> merge           2 argocd app rollback orders-api-prod 41
3 agent syncs 1.4.2                           3 cluster runs 1.4.2, Git says 1.5.0 (OutOfSync)
4 Git == cluster, audit trail intact          4 must still revert Git, then re-enable auto-sync

سناریوهای واقعی:

  • پسرفت فقط در Image: Commit مربوط به Promotion را Revert کنید؛ دو خط تغییر.
  • Migration قبلاً اجرا شده است؛ برگرداندن Image، Schema را برنمی‌گرداند. Migration سازگار با گذشته با الگوی Expand/Contract است که Rollback تصویر را امن می‌کند.
  • Upgrade خراب Chart زیر Flux: Remediation انتشار را برمی‌گرداند؛ Revert بعدی آن را در همان وضعیت نگه می‌دارد.
روشGit پس از آن هماهنگ استبا Auto-sync کار می‌کندممیزی
git revert و SyncبلهبلهCommit و PR
argocd app rollbackخیرخیر؛ باید خاموش شودفقط تاریخچهٔ Argo CD
Remediation در Flux HelmReleaseتا Revert خیربلهرویدادها
kubectl rollout undoخیر؛ Self-heal برمی‌گرداندبا Agent درگیر می‌شودندارد

راه‌حل: مرحلهٔ «Revert آخرین Promotion» را در Runbook داشته باشید و برای PR بازگشت، تأیید سریع مجاز کنید.

تحویل تدریجی (Progressive delivery): Argo Rollouts و Flagger تکمیلی ​

به زبان ساده: GitOps تعیین می‌کند چه نسخه‌ای اجرا شود؛ ابزار تحویل تدریجی تعیین می‌کند ترافیک با چه سرعتی به آن برود و با سنجهٔ بد Rollback می‌کند.

بدفهمی رایج: «Canary به Pipeline تغییر مرحله‌ای ترافیک نیاز دارد.» در GitOps، Commit فقط یک‌بار نسخه را تغییر می‌دهد؛ Controller داخل Cluster، Canary را اجرا می‌کند.

تعریف: Argo Rollouts، "is a Kubernetes controller and set of CRDs which provide advanced deployment capabilities such as blue-green, canary, canary analysis, experimentation, and progressive delivery features to Kubernetes". Flagger، "is a progressive delivery tool that automates the release process for applications running on Kubernetes ... gradually shifting traffic to the new version while measuring metrics". راهبردهای Canary، A/B و Blue/Green را از طریق Service mesh یا Ingress مانند NGINX، Istio، Linkerd و Gateway API اجرا می‌کند. راهبردها، تحلیل و تقسیم ترافیک در راهبردهای استقرار، شامل Argo Rollouts و Flagger، آموزش داده شده‌اند.

text
1  promotion commit: Rollout image 1.5.0
2  Argo CD syncs the Rollout object (health Progressing / Suspended while paused)
3  Rollouts controller: 10% -> analysis (Prometheus error rate) -> 50% -> 100%
4  bad metrics -> abort -> stable version keeps traffic; Git still says 1.5.0 -> revert

سناریوهای واقعی: Flagger همراه Flux برای Laravel پشت NGINX؛ Argo Rollouts همراه Argo CD و Istio برای سرویس Go.

ابزارهمراه طبیعیاشیا
Argo RolloutsArgo CD؛ هم‌خانواده‌اند و سلامت Rollout در برنامه دیده می‌شودRollout، AnalysisTemplate
FlaggerFlux؛ اکوسیستم نگهدارندگان مشترکCanary، MetricTemplate

راه‌حل: وضعیت Health کنترل‌گر تحویل تدریجی را به Agent معرفی کنید تا شکست تحلیل به‌شکل Degraded دیده شود.

GitOps برای زیرساخت: آشنایی با Crossplane و tf-controller تکمیلی ​

به زبان ساده: همین حلقه منابع ابری را هم مدیریت می‌کند؛ توصیف پایگاه داده را Commit کنید تا Controller آن را بسازد و پیوسته آشتی‌دهی کند.

بدفهمی رایج: «GitOps فقط برای Workloadهای Kubernetes است.» هر API اعلانی با Controller آشتی‌دهنده واجد شرایط است.

تعریف، آشنایی با Crossplane: "Crossplane is a control plane framework for platform engineering"؛ "Control planes expose an API. You use the API to tell the control plane what software it should configure and how - this is your desired state." Argo CD یا Flux منابع Crossplane را Apply می‌کند؛ Providerهای Crossplane وضعیت ابر را آشتی‌دهی می‌کنند. tf-controller: "Tofu Controller (previously known as Weave TF-Controller) is a controller for Flux to reconcile OpenTofu and Terraform resources in the GitOps way". از خودکارسازی کامل با approvePlan: auto تا صرفاً "Drift Detection Model" را پشتیبانی می‌کند. در روش Plan و تأیید، "You make change to the field .spec.approvePlan, commit and push". خود Terraform در زیرساخت به‌شکل کد است.

yaml
# Tofu Controller (from its getting-started guide): plan and apply a Terraform module
# from a Flux source, then keep detecting drift at each interval
apiVersion: infra.contrib.fluxcd.io/v1alpha2
kind: Terraform
metadata:
  name: helloworld
  namespace: flux-system
spec:
  interval: 1m
  approvePlan: auto
  path: ./
  sourceRef:
    kind: GitRepository
    name: helloworld
    namespace: flux-system
text
1  commit: Terraform object (approvePlan: auto) for the shop's S3 bucket module
2  Tofu Controller runner pod: plan -> apply; TFSTATE stored as a Secret
3  every interval: drift detection; a console edit -> new plan applied

سناریوهای واقعی: ساخت پایگاه دادهٔ هر محیط همراه برنامه؛ آشتی‌دهی سیاست IAM از Git؛ گزارش Drift فقط‌خواندنی برای Terraform قدیمی.

ابزارمدلDrift
CrossplaneCRDهای Kubernetes برای منابع ابر و Compositionهاپیوسته با Controllerهای Provider
Tofu Controller یا tf-controllerاجرای Terraform/OpenTofu با Fluxدر هر بازه؛ "enabled by default"
Terraform در CIPush با کار Plan/Applyفقط هنگام اجرای Job

راه‌حل: پیش از اجازهٔ Apply به Controller، برای Terraform موجود از تشخیص Drift فقط‌خواندنی شروع کنید.

مشاهده‌پذیری (Observability): سنجه‌های Sync و Prometheus مهم ​

به زبان ساده: سنجه‌های (Metrics) Agent را جمع کنید، برای برنامه‌ای که OutOfSync یا Degraded می‌ماند هشدار بدهید و مدت Reconciliation را نمودار کنید.

بدفهمی رایج: «اعلان Slack همان پایش است.» اعلان رویداد است؛ وضعیت و روند هم لازم دارید، مثلاً همین حالا چند برنامه OutOfSync هستند؟

تعریف: application-controller در Argo CD سنجه‌ها را "at the argocd-metrics:8082/metrics endpoint" ارائه می‌کند: argocd_app_info با برچسب‌های sync_status و health_status، argocd_app_sync_total، argocd_app_reconcile به‌شکل Histogram، argocd_app_k8s_request_total، argocd_app_condition و argocd_app_orphaned_resources_count. api-server روی argocd-server-metrics:8083 و repo-server روی argocd-repo-server:8084 با argocd_git_request_total هستند. Controllerهای Flux، "export Prometheus metrics at port 8080 in the standard /metrics path": gotk_reconcile_duration_seconds_*، gotk_cache_events_total و سنجه‌های controller-runtime. وضعیت منبع با gotk_resource_info و ready و suspended از kube-state-metrics می‌آید؛ مانند flux2-monitoring-example. ابزارهای سطح Cluster در مشاهده‌پذیری Kubernetes آمده‌اند.

text
# Argo CD: apps not Synced for 15 minutes (alert)
max by (name, project) (argocd_app_info{sync_status!="Synced"}) == 1
# Argo CD: apps Degraded
max by (name) (argocd_app_info{health_status="Degraded"}) == 1
# Flux: p95 reconcile duration per kind
histogram_quantile(0.95, sum by (kind, le) (rate(gotk_reconcile_duration_seconds_bucket[10m])))
# Flux (kube-state-metrics): objects not Ready
gotk_resource_info{ready="False"}
text
alert pipeline
1  Prometheus scrapes argocd-metrics:8082 and Flux :8080 (+ kube-state-metrics)
2  rule "OutOfSync > 15m" fires -> Alertmanager -> on-call
3  on-call: argocd app diff / flux get kustomizations -> cause (drift, failed hook, bad render)

سناریوهای واقعی: داشبورد سنجهٔ Sync برای هر تیم؛ جهش argocd_git_request_total پس از قطعی Webhook؛ Kustomization گیرکرده در DependencyNotReady برای یک ساعت.

سیگنالArgo CDFlux
وضعیت Syncargocd_app_info{sync_status}gotk_resource_info{ready} از KSM
سلامتargocd_app_info{health_status}Ready همراه دلیل
هزینهٔ Reconciliationargocd_app_reconcilegotk_reconcile_duration_seconds
Syncهاargocd_app_sync_totalرویدادها و Alertها

راه‌حل: پیش از اولین برنامهٔ Production، دو قاعدهٔ هشدار OutOfSync و Degraded را اضافه کنید.

ضدالگوها: kubectl apply از CI، cluster-admin در CI، Config کنار کد و شاخه‌های بلندعمر حیاتی ​

به زبان ساده: تیم نام GitOps را به کار می‌برد، ولی هنوز Push می‌کند، اعتبارنامهٔ همه‌کاره به اشتراک می‌گذارد یا تفاوت محیط‌ها را پنهان می‌کند.

بدفهمی رایج: «Argo CD داریم، پس امن هستیم.» Pipeline که هنوز kubectl apply را با Token دارای cluster-admin اجرا می‌کند همهٔ خطرهای Push را دارد؛ فقط Agent رقابت‌کننده هم به آن اضافه شده است.

تعریف: ضدالگوهای (Anti-patterns) تکرارشونده:

  • اجرای kubectl apply از CI: CI مستقیم مستقر می‌کند؛ کسی مسئول Drift و Prune نیست.
  • cluster-admin در CI: kubeconfig با این دسترسی در Secretsِ CI؛ یک افشا برای تصاحب کامل کافی است.
  • Config در App repo: Manifest کنار کد و ثبت Tag توسط CI در همان repo؛ هشدار Argo CD این است که "can trigger an infinite loop of build jobs and Git commit triggers".
  • شاخهٔ بلندعمر (Long-lived branches) برای هر محیط: Drift ناشی از Merge؛ چیدمان Repository.
  • Tag تغییرپذیر (Mutable tags) مانند latest در Git: Commit دیگر بایت مشخصی را معرفی نمی‌کند.
  • Base دوردست روی HEAD: Manifestها "change their meaning from one day to the next".
  • همه‌چیز در AppProject با نام default و ApplicationSet قابل ویرایش توسط غیرمدیر.
  • درگیری Self-heal با Controller، چون زیر HPA تعداد Replica در Git نوشته شده است.
text
A typical "hybrid" failure
1  Argo CD syncs orders-api 1.4.2 from Git (selfHeal on)
2  legacy CI job still runs: kubectl set image ... :latest
3  Argo CD reverts to 1.4.2 within seconds; CI job reports success
4  team believes 'latest' is deployed; debugging the wrong version for hours

سناریوهای واقعی: Workflow قبل در Go، چهار مورد را در دوازده خط نشان می‌دهد.

ضدالگوجایگزین
kubectl apply از CICI، Commit یا PR می‌سازد؛ Agent، Apply می‌کند
cluster-admin در CIاعتبارنامهٔ Cluster در CI نباشد؛ اگر تحریک Sync لازم است Token محدود Project در Argo CD
Config در App repoConfig repository یا ارجاع از آن به App repo به‌عنوان Base
شاخهٔ هر محیطپوشهٔ هر محیط روی main
latest در GitTag انتشار و Digest؛ نوشتن با Image automation
Project با نام defaultAppProject هر تیم؛ ApplicationSet فقط برای مدیر

راه‌حل: کار Deploy را حذف کنید، به CI فقط Token محدود Config repo بدهید و تست‌های Repository زیر را اضافه کنید.

سازوکار (Mechanics) ​

یک Reconciliation در Argo CD، گام‌به‌گام ​

text
application-controller, per Application, every timeout.reconciliation (120s + jitter) or on refresh
1  resolve targetRevision (branch/tag/semver) to a commit SHA via repo-server (ls-remote)
2  repo-server: manifests for (repoURL, SHA, path, tool options) - cached by that key
3  normalise desired objects; read live objects from the controller's watch cache,
   matched by tracking (annotation argocd.argoproj.io/tracking-id by default)
4  diff with ignoreDifferences and compare options -> per-resource Synced/OutOfSync;
   tracked objects absent from desired -> marked for pruning
5  health: built-in checks + Lua customizations -> worst child wins
6  if automated and OutOfSync (and this SHA+params not already synced, or selfHeal):
     sync operation: PreSync hooks -> waves (lowest first, 2s apart, wait healthy)
     -> PostSync hooks; prune (reverse wave order, PruneLast at the end)
7  write status (sync, health, operationState, history entry) -> metrics, notifications

یک Reconciliation در Flux، گام‌به‌گام ​

text
source-controller (GitRepository, every .spec.interval)
1  fetch ref -> if new revision: package tar.gz artifact, record revision main@sha1:<sha>, emit event
kustomize-controller (Kustomization, on interval or new artifact revision)
2  check dependsOn Ready -> else DependencyNotReady, requeue
3  download artifact, kustomize build .spec.path, SOPS decrypt, postBuild substitute
4  server-side apply dry-run against the cluster -> set of changed objects (drift included)
5  apply in stages; prune objects in the stored inventory missing from this build
6  health checks (wait / healthChecks) with .spec.timeout
7  Ready condition + inventory + lastAppliedRevision -> events -> notification-controller

تنظیمات (Knobs) ​

تنظیممحلپیش‌فرض یا مثالاثر
timeout.reconciliationargocd-cm120s با 60s نوسانبازهٔ Poll گیت؛ 0 آن را خاموش می‌کند که توصیه نمی‌شود
--self-heal-timeout-secondsapplication-controller5تأخیر پیش از Sync خود‌ترمیمی
ARGOCD_SYNC_WAVE_DELAYEnvironment کنترل‌گر2 sمکث میان Waveها
application.resourceTrackingMethodargocd-cmannotationتشخیص مالکیت منابع توسط Argo CD
requeueAfterSecondsمولد ApplicationSetGit برابر 180 s، PR برابر 1800 sPoll مولد
revisionHistoryLimitApplication10ورودی‌های argocd app rollback
syncWindowsAppProjectallow/deny و cronپنجرهٔ مجاز تغییر
.spec.intervalهر شیء Fluxمثلاً 10mآهنگ Reconciliation و Drift
.spec.retryIntervalKustomizationبرابر intervalتلاش پس از شکست
.spec.timeoutKustomization، HelmReleaseمثلاً 5mسقف زمان Build/Apply/Health
--no-cross-namespace-refsControllerهای Fluxfalseمحدودسازی مستاجرها
--no-remote-baseskustomize-controllerfalseمنع Base دوردست Kustomize
driftDetection.modeHelmReleaseاختیاری؛ warn یا enabledتشخیص یا اصلاح Drift در Helm
update.strategyImageUpdateAutomationSettersبازنویسی بر پایهٔ نشانگر

دلیل وضعیت‌ها و پیام‌هایی که می‌بینید ​

پیام یا دلیل، عین مستنداتابزارمعنیراه‌حل
the server could not find the requested resourceArgo CDCR که CRD آن در Cluster یا Sync نیستCRD در Wave زودتر یا SkipDryRunOnMissingResource=true
ComparisonError ... doesn't match $setElementOrder listArgo CDکلید تکراری در Merge list مانند متغیر محیطیحذف تکرار در Manifest
kustomization path not found: stat /tmp/kustomization-.../invalid: no such file or directory با ArtifactFailedFlux.spec.path نادرستاصلاح مسیر؛ تست‌های فصل آن را می‌گیرند
couldn't find remote ref "refs/heads/invalid" با GitOperationFailedFluxشاخه وجود ندارداصلاح ref.branch
DependencyNotReadyFluxیک dependsOn یا شیء ارجاع‌شده Ready نیستابتدا وابستگی را اصلاح کنید
referenced ImageRepository does not existFluxImagePolicy به ImageRepository ناموجود اشاره داردآن را در همان Namespace بسازید
Failed to install after 1 attempt(s) با RetriesExceededFlux helm-controllerتلاش‌های Remediation تمام شدهخواندن رویداد Helm؛ Revert یا اصلاح Values
PruneFailed، BuildFailed، HealthCheckFailed، ReconciliationFailedFlux Kustomizationدستهٔ شکستflux events --for Kustomization/<name>

Go ​

Go در GitOps دو نقش دارد. خود سرویس باید سلامت را قابل مشاهده کند؛ Endpoint آمادگی (Readiness) و زنده‌بودن (Liveness) و خاموشی آرام (Graceful shutdown)، چون هر دو Agent از آن برای قضاوت Rollout استفاده می‌کنند. کد آن در Image و Dockerfile است و تکرار نمی‌شود. اینجا سه ابزار کوچک برای CIِ Config repository داریم، با کتابخانهٔ استاندارد و gopkg.in/yaml.v3: مدل Drift، ویرایشگر Image tag برای PR ارتقا و تست سیاست Repository. در repo واقعی Module در tools/ است، همان‌طور که Workflow می‌گوید؛ اینجا در docs/snippets/platform/gitops-argocd-flux/go با Module به نام academy/gitops-argocd-flux و go 1.24 قرار دارد.

قبل (Before) ​

استقرار Push که بیشتر تیم‌ها از آن شروع می‌کنند و دلیل GitOps نبودنش:

yaml
# BEFORE (anti-pattern): push-based deploy from CI. Works on day one; every line below
# is a GitOps problem. Kept to contrast with the config-repo workflows next to it.
name: deploy
on:
  push:
    branches: [main]
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      # 1. a long-lived kubeconfig with cluster-admin rights lives in CI secrets:
      #    anyone who can change this workflow (or a compromised action) owns the cluster
      - run: echo "${{ secrets.PROD_KUBECONFIG }}" > kubeconfig
      # 2. the cluster API must be reachable from the CI runners (a public endpoint
      #    or a network path from the CI provider into production)
      # 3. "latest" is not a version: Git does not say what runs, rollback is guesswork
      - run: kubectl --kubeconfig kubeconfig set image deployment/orders-api orders-api=ghcr.io/acme/orders-api:latest -n shop-prod
      # 4. apply runs once per push; a later kubectl edit (drift) is never noticed or reverted,
      #    and objects deleted from the repo are never pruned
      - run: kubectl --kubeconfig kubeconfig apply -k deploy/overlays/prod

بعد (After) ​

۱. مدل Drift. تابع drift.Compare اشیای مطلوب و زنده را با group/kind/namespace/name تطبیق می‌دهد و فقط فیلدهای تعیین‌شده در وضعیت مطلوب را مقایسه می‌کند؛ پس پیش‌فرض‌هایی مانند clusterIP، imagePullPolicy یا strategy، Drift نیستند. فهرست‌های نام‌دار مانند containers، ports و env را شبیه Strategic merge با نام تطبیق می‌دهد؛ قواعد Ignore بر اساس JSON pointer با Escapeِ ~1 را رعایت می‌کند؛ شیء رهگیری‌شده و حذف‌شده از Git را نیازمند Prune می‌داند و شیء رهگیری‌نشده مانند kube-root-ca.crt را نادیده می‌گیرد. این مدل آموزشی است؛ الگوریتم خود Argo CD یا Flux نیست، چون آن‌ها Normalization و Server-side dry-run دارند، اما قواعد مدل از رفتار آن‌ها گرفته شده است.

go
// Package drift is a teaching model of what a GitOps agent does on every reconcile:
// compare the desired objects (rendered from Git) with the live objects (read from the
// API server) and report which are Synced, OutOfSync, Missing or would be pruned.
//
// It is NOT Argo CD's or Flux's algorithm. Argo CD normalises objects and can diff with a
// server-side dry-run; Flux's kustomize-controller asks the API server for a server-side
// apply dry-run. Both share the two rules modelled here: only fields the desired state
// sets are compared (the API server fills in defaults, so live objects always have more
// fields), and configured fields can be ignored (Argo CD ignoreDifferences, Flux
// driftDetection.ignore). Pruning is decided by ownership tracking, never by guessing.
package drift

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"reflect"
	"sort"
	"strconv"
	"strings"

	"gopkg.in/yaml.v3"
)

// TrackingAnnotation is the annotation Argo CD's default "annotation" tracking method
// writes on every object it manages: "<app>:<group>/<kind>:<namespace>/<name>".
const TrackingAnnotation = "argocd.argoproj.io/tracking-id"

// Object is one Kubernetes manifest as a generic map.
type Object map[string]any

// Key identifies an object: group/kind plus namespace/name.
func (o Object) Key() string {
	api, _ := o["apiVersion"].(string)
	kind, _ := o["kind"].(string)
	group := ""
	if i := strings.Index(api, "/"); i >= 0 {
		group = api[:i]
	}
	meta, _ := o["metadata"].(map[string]any)
	ns, _ := meta["namespace"].(string)
	name, _ := meta["name"].(string)
	return group + "/" + kind + ":" + ns + "/" + name
}

func (o Object) annotation(key string) string {
	meta, _ := o["metadata"].(map[string]any)
	ann, _ := meta["annotations"].(map[string]any)
	v, _ := ann[key].(string)
	return v
}

// Parse splits a multi-document YAML stream into objects, skipping empty documents.
func Parse(stream []byte) ([]Object, error) {
	dec := yaml.NewDecoder(bytes.NewReader(stream))
	var out []Object
	for {
		// decode into a plain map: decoding into Object would make every nested map an
		// Object too, and the type switches below expect map[string]any
		var o map[string]any
		err := dec.Decode(&o)
		if errors.Is(err, io.EOF) {
			return out, nil
		}
		if err != nil {
			return nil, fmt.Errorf("document %d: %w", len(out)+1, err)
		}
		if len(o) == 0 {
			continue
		}
		out = append(out, Object(o))
	}
}

// Change is one field whose live value differs from the desired value.
type Change struct {
	Path    string // JSON pointer, e.g. /spec/template/spec/containers/orders-api/image
	Desired any
	Live    any // nil when the field is missing in the live object
}

func (c Change) String() string {
	if c.Live == nil {
		return fmt.Sprintf("%s: missing in live (desired %v)", c.Path, c.Desired)
	}
	return fmt.Sprintf("%s: desired %v, live %v", c.Path, c.Desired, c.Live)
}

// Options configures a comparison.
type Options struct {
	// App is the Application name used to recognise objects this app owns (tracking).
	App string
	// Ignore lists JSON pointers that are never reported (ignoreDifferences).
	// A "~1" stands for "/" inside a key, as in RFC 6901.
	Ignore []string
}

// skipped are paths no desired state should own: the API server or controllers write them.
var skipped = []string{"/status", "/metadata/managedFields", "/metadata/resourceVersion",
	"/metadata/uid", "/metadata/generation", "/metadata/creationTimestamp"}

// Fields compares one desired object with its live counterpart.
func Fields(desired, live Object, opts Options) []Change {
	ignore := append(append([]string{}, skipped...), opts.Ignore...)
	var out []Change
	walk("", map[string]any(desired), map[string]any(live), ignore, &out)
	sort.Slice(out, func(i, j int) bool { return out[i].Path < out[j].Path })
	return out
}

func escape(k string) string { return strings.ReplaceAll(strings.ReplaceAll(k, "~", "~0"), "/", "~1") }

func ignored(path string, ignore []string) bool {
	for _, p := range ignore {
		if path == p || strings.HasPrefix(path, p+"/") {
			return true
		}
	}
	return false
}

func walk(path string, desired, live any, ignore []string, out *[]Change) {
	if ignored(path, ignore) {
		return
	}
	switch d := desired.(type) {
	case map[string]any:
		l, _ := live.(map[string]any)
		for k, dv := range d {
			p := path + "/" + escape(k)
			lv, ok := l[k]
			if !ok {
				if !ignored(p, ignore) && !empty(dv) {
					*out = append(*out, Change{Path: p, Desired: dv})
				}
				continue
			}
			walk(p, dv, lv, ignore, out)
		}
	case []any:
		l, _ := live.([]any)
		if named(d) {
			// lists of named items (containers, ports, env) are matched by name,
			// the way a strategic merge patch does, not by position
			byName := map[string]any{}
			for _, it := range l {
				if m, ok := it.(map[string]any); ok {
					if n, ok := m["name"].(string); ok {
						byName[n] = m
					}
				}
			}
			for _, it := range d {
				n := it.(map[string]any)["name"].(string)
				p := path + "/" + escape(n)
				lv, ok := byName[n]
				if !ok {
					*out = append(*out, Change{Path: p, Desired: it})
					continue
				}
				walk(p, it, lv, ignore, out)
			}
			return
		}
		if !reflect.DeepEqual(normalise(d), normalise(l)) {
			*out = append(*out, Change{Path: path, Desired: d, Live: live})
		}
	default:
		if !reflect.DeepEqual(normalise(desired), normalise(live)) {
			*out = append(*out, Change{Path: path, Desired: desired, Live: live})
		}
	}
}

// named reports whether every element is a map with a string "name" key.
func named(list []any) bool {
	if len(list) == 0 {
		return false
	}
	for _, it := range list {
		m, ok := it.(map[string]any)
		if !ok {
			return false
		}
		if _, ok := m["name"].(string); !ok {
			return false
		}
	}
	return true
}

// empty treats {} and [] in the desired state as "no opinion" (Kustomize leaves
// placeholders like selector: {} that it fills in, and the API server drops empties).
func empty(v any) bool {
	switch t := v.(type) {
	case map[string]any:
		return len(t) == 0
	case []any:
		return len(t) == 0
	}
	return false
}

// normalise makes 8080 and "8080" or 1 and 1.0 compare equal, as the API server does
// for int-or-string fields once they are stored.
func normalise(v any) any {
	switch t := v.(type) {
	case int:
		return strconv.Itoa(t)
	case float64:
		return strconv.FormatFloat(t, 'f', -1, 64)
	case []any:
		out := make([]any, len(t))
		for i, x := range t {
			out[i] = normalise(x)
		}
		return out
	case map[string]any:
		out := make(map[string]any, len(t))
		for k, x := range t {
			out[k] = normalise(x)
		}
		return out
	}
	return v
}

// Status is the per-object result, named as Argo CD names them.
type Status string

const (
	Synced        Status = "Synced"
	OutOfSync     Status = "OutOfSync"
	Missing       Status = "Missing"         // desired, not in the cluster: sync will create it
	RequiresPrune Status = "RequiresPruning" // owned by the app, gone from Git: prune deletes it
)

// Result is one object's status with its changes.
type Result struct {
	Key     string
	Status  Status
	Changes []Change
}

// Report is the outcome of comparing a whole application.
type Report struct {
	Results []Result
}

// Synced reports whether the application as a whole is in sync.
func (r Report) Synced() bool {
	for _, res := range r.Results {
		if res.Status != Synced {
			return false
		}
	}
	return true
}

// Compare matches desired and live objects by key. A live object that is not desired is
// reported only if its tracking annotation says this app owns it; anything else in the
// namespace (objects made by controllers or by other tools) is none of the app's business.
func Compare(desired, live []Object, opts Options) Report {
	liveBy := map[string]Object{}
	for _, o := range live {
		liveBy[o.Key()] = o
	}
	var rep Report
	seen := map[string]bool{}
	for _, d := range desired {
		k := d.Key()
		seen[k] = true
		l, ok := liveBy[k]
		if !ok {
			rep.Results = append(rep.Results, Result{Key: k, Status: Missing})
			continue
		}
		ch := Fields(d, l, opts)
		st := Synced
		if len(ch) > 0 {
			st = OutOfSync
		}
		rep.Results = append(rep.Results, Result{Key: k, Status: st, Changes: ch})
	}
	for _, l := range live {
		k := l.Key()
		if seen[k] || opts.App == "" {
			continue
		}
		if strings.HasPrefix(l.annotation(TrackingAnnotation), opts.App+":") {
			rep.Results = append(rep.Results, Result{Key: k, Status: RequiresPrune})
		}
	}
	sort.Slice(rep.Results, func(i, j int) bool { return rep.Results[i].Key < rep.Results[j].Key })
	return rep
}
go
package drift

import (
	"os"
	"strings"
	"testing"
)

func load(t *testing.T, name string) []Object {
	t.Helper()
	b, err := os.ReadFile("testdata/" + name)
	if err != nil {
		t.Fatal(err)
	}
	objs, err := Parse(b)
	if err != nil {
		t.Fatal(err)
	}
	return objs
}

func byKey(r Report) map[string]Result {
	m := map[string]Result{}
	for _, res := range r.Results {
		m[res.Key] = res
	}
	return m
}

// The rendered overlay against a live cluster with defaults, status, an HPA replica
// count, a manual image change and an orphaned ConfigMap.
func TestCompareRealisticLiveState(t *testing.T) {
	desired := load(t, "desired-orders-api-prod.yaml")
	live := load(t, "live-orders-api-prod.yaml")
	rep := Compare(desired, live, Options{App: "orders-api-prod", Ignore: []string{"/spec/replicas"}})
	m := byKey(rep)

	if got := m["/Service:shop-prod/orders-api"].Status; got != Synced {
		t.Errorf("Service: defaulted fields (clusterIP, protocol, type) must not count as drift, got %s %v",
			got, m["/Service:shop-prod/orders-api"].Changes)
	}
	dep := m["apps/Deployment:shop-prod/orders-api"]
	if dep.Status != OutOfSync || len(dep.Changes) != 1 {
		t.Fatalf("Deployment: want exactly one change (the image), got %s %v", dep.Status, dep.Changes)
	}
	c := dep.Changes[0]
	if c.Path != "/spec/template/spec/containers/orders-api/image" || !strings.Contains(c.Live.(string), "1.4.3-hotfix") {
		t.Errorf("unexpected change %v", c)
	}
	if got := m["/ConfigMap:shop-prod/orders-api-flags"].Status; got != RequiresPrune {
		t.Errorf("tracked ConfigMap missing from Git must require pruning, got %q", got)
	}
	if _, ok := m["/ConfigMap:shop-prod/kube-root-ca.crt"]; ok {
		t.Error("an untracked object must never be reported (and never pruned)")
	}
	if rep.Synced() {
		t.Error("report must be OutOfSync")
	}
}

// Without the ignore rule, the HPA's replica count is reported as drift: the reason for
// Argo CD ignoreDifferences and Flux driftDetection.ignore on /spec/replicas.
func TestReplicasDriftWithoutIgnore(t *testing.T) {
	desired := load(t, "desired-orders-api-prod.yaml")
	live := load(t, "live-orders-api-prod.yaml")
	desired[1]["spec"].(map[string]any)["replicas"] = 3
	dep := byKey(Compare(desired, live, Options{App: "orders-api-prod"}))["apps/Deployment:shop-prod/orders-api"]
	found := false
	for _, c := range dep.Changes {
		if c.Path == "/spec/replicas" {
			found = true
		}
	}
	if !found {
		t.Errorf("want /spec/replicas drift, got %v", dep.Changes)
	}
	dep = byKey(Compare(desired, live, Options{App: "orders-api-prod", Ignore: []string{"/spec/replicas"}}))["apps/Deployment:shop-prod/orders-api"]
	for _, c := range dep.Changes {
		if c.Path == "/spec/replicas" {
			t.Errorf("ignored path reported: %v", c)
		}
	}
}

func TestMissingObjectAndMissingField(t *testing.T) {
	desired := load(t, "desired-orders-api-prod.yaml")
	rep := Compare(desired, nil, Options{App: "orders-api-prod"})
	for _, r := range rep.Results {
		if r.Status != Missing {
			t.Errorf("%s: want Missing, got %s", r.Key, r.Status)
		}
	}
	d := Object{"spec": map[string]any{"paused": false, "selector": map[string]any{}}}
	l := Object{"spec": map[string]any{}}
	ch := Fields(d, l, Options{})
	if len(ch) != 1 || ch[0].Path != "/spec/paused" || ch[0].Live != nil {
		t.Errorf("want one missing field /spec/paused (empty selector placeholder ignored), got %v", ch)
	}
}

func TestNamedListsMatchByName(t *testing.T) {
	d := Object{"env": []any{
		map[string]any{"name": "A", "value": "1"},
		map[string]any{"name": "B", "value": "2"},
	}}
	l := Object{"env": []any{
		map[string]any{"name": "B", "value": "2"},
		map[string]any{"name": "A", "value": "1"},
	}}
	if ch := Fields(d, l, Options{}); len(ch) != 0 {
		t.Errorf("reordered named list is not drift, got %v", ch)
	}
	l["env"].([]any)[0].(map[string]any)["value"] = "9"
	ch := Fields(d, l, Options{})
	if len(ch) != 1 || ch[0].Path != "/env/B/value" {
		t.Errorf("want /env/B/value, got %v", ch)
	}
}

func TestEscapedIgnorePointer(t *testing.T) {
	d := Object{"metadata": map[string]any{"labels": map[string]any{"node-role.kubernetes.io/worker": "x"}}}
	l := Object{"metadata": map[string]any{"labels": map[string]any{"node-role.kubernetes.io/worker": "y"}}}
	if ch := Fields(d, l, Options{Ignore: []string{"/metadata/labels/node-role.kubernetes.io~1worker"}}); len(ch) != 0 {
		t.Errorf("~1-escaped pointer must match, got %v", ch)
	}
}
go
// Command driftdiff compares a rendered desired state with a live state dump and prints
// an Argo CD-style sync report. Exit status: 0 Synced, 1 OutOfSync, 2 usage or input error.
//
//	kubectl kustomize apps/orders-api/overlays/prod > desired.yaml
//	kubectl get svc,deploy,cm -n shop-prod -o yaml > live.yaml   # a List; see below
//	driftdiff -desired desired.yaml -live live.yaml -app orders-api-prod -ignore /spec/replicas
//
// The live file must be a stream of objects (kubectl get -o yaml prints a v1 List; split
// it, or use one "kubectl get <kind>/<name> -o yaml" per object separated by "---").
package main

import (
	"flag"
	"fmt"
	"os"
	"strings"

	"academy/gitops-argocd-flux/drift"
)

func main() {
	desiredPath := flag.String("desired", "", "rendered manifests (kustomize build / helm template)")
	livePath := flag.String("live", "", "live objects as a YAML stream")
	app := flag.String("app", "", "application name used in the tracking annotation")
	ignore := flag.String("ignore", "", "comma-separated JSON pointers to ignore")
	flag.Parse()
	if *desiredPath == "" || *livePath == "" {
		flag.Usage()
		os.Exit(2)
	}
	desired, err := read(*desiredPath)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(2)
	}
	live, err := read(*livePath)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(2)
	}
	opts := drift.Options{App: *app}
	if *ignore != "" {
		opts.Ignore = strings.Split(*ignore, ",")
	}
	rep := drift.Compare(desired, live, opts)
	for _, r := range rep.Results {
		fmt.Printf("%-16s %s\n", r.Status, r.Key)
		for _, c := range r.Changes {
			fmt.Printf("    %s\n", c)
		}
	}
	if rep.Synced() {
		fmt.Println("application: Synced")
		return
	}
	fmt.Println("application: OutOfSync")
	os.Exit(1)
}

func read(path string) ([]drift.Object, error) {
	b, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}
	objs, err := drift.Parse(b)
	if err != nil {
		return nil, fmt.Errorf("%s: %w", path, err)
	}
	return objs, nil
}

۲. ویرایش Image tag. تابع imagebump.Bump یک ورودی images: را خط‌به‌خط تغییر می‌دهد؛ PR ارتقا دقیقاً دو خط تغییر دارد و Commentها می‌مانند. ApplySetters راهبرد Setters در Flux را روی $imagepolicy مدل می‌کند: ارجاع کامل، :tag، :name و :digest؛ سیاست ناشناخته خطاست و اجرای دوم تغییری نمی‌دهد. Newest یک ImagePolicy با filterTags و بازهٔ semver را مدل می‌کند؛ ترتیب عددی است، پس 2.10.0 از 2.8.1 جدیدتر است و پیش‌انتشارها و Tagهای sha- کنار می‌روند.

go
// Package imagebump models the two ways a tag reaches Git in this chapter.
//
//   - Bump edits one entry of a kustomization.yaml "images:" list, as a promotion pull
//     request (or "kustomize edit set image", or Argo CD Image Updater's
//     writeBackTarget: kustomization) does.
//   - ApplySetters rewrites every value that carries a Flux setter marker such as
//     # {"$imagepolicy": "flux-system:shop-app:tag"}, as Flux's image-automation-controller
//     does with update.strategy: Setters.
//   - BumpHelmImage does the same for a HelmRelease's values.image block, so one
//     promotion moves every place that names the prod version.
//   - Newest picks a tag the way a Flux ImagePolicy with filterTags + a semver range does.
//
// Both editors work line by line so comments, markers and key order survive: a YAML
// re-encode would reformat the file and make every bump PR noisy. This is a teaching
// model, not the controllers' code.
package imagebump

import (
	"encoding/json"
	"fmt"
	"regexp"
	"strconv"
	"strings"
)

// Bump sets newTag (and digest, if non-empty) on the images entry whose name is image.
// It returns an error if the file has no such entry.
func Bump(src []byte, image, tag, digest string) ([]byte, error) {
	lines := strings.Split(string(src), "\n")
	start, indent := -1, ""
	inImages := false
	for i, l := range lines {
		t := strings.TrimSpace(l)
		if !strings.HasPrefix(l, " ") && !strings.HasPrefix(l, "-") && t != "" && !strings.HasPrefix(t, "#") {
			inImages = strings.HasPrefix(t, "images:")
			continue
		}
		if inImages && (t == "- name: "+image || t == "- name: \""+image+"\"") {
			start = i
			indent = l[:strings.Index(l, "-")] + "  "
			break
		}
	}
	if start < 0 {
		return nil, fmt.Errorf("no images entry named %q", image)
	}
	// the entry runs until the next "- " at the same indent or a less-indented line
	end := start + 1
	for end < len(lines) {
		l := lines[end]
		if strings.TrimSpace(l) == "" || !strings.HasPrefix(l, indent) || strings.HasPrefix(strings.TrimSpace(l), "- ") && len(l)-len(strings.TrimLeft(l, " ")) < len(indent) {
			break
		}
		end++
	}
	// copy: appending to a sub-slice of lines would overwrite the line after the entry
	entry := append([]string{}, lines[start+1:end]...)
	entry = setKey(entry, indent, "newTag", strconv.Quote(tag))
	if digest != "" {
		entry = setKey(entry, indent, "digest", digest)
	}
	out := append(append(append([]string{}, lines[:start+1]...), entry...), lines[end:]...)
	return []byte(strings.Join(out, "\n")), nil
}

// BumpHelmImage sets tag (and digest) in the YAML mapping that holds
// "repository: <repository>" (a HelmRelease's spec.values.image, for example). Sibling
// keys are matched at the repository line's indentation; comments are kept.
func BumpHelmImage(src []byte, repository, tag, digest string) ([]byte, error) {
	lines := strings.Split(string(src), "\n")
	at := -1
	for i, l := range lines {
		t := strings.TrimSpace(l)
		if t == "repository: "+repository || t == "repository: \""+repository+"\"" {
			at = i
			break
		}
	}
	if at < 0 {
		return nil, fmt.Errorf("no \"repository: %s\" line", repository)
	}
	indent := lines[at][:len(lines[at])-len(strings.TrimLeft(lines[at], " "))]
	start, end := at, at+1
	for start > 0 && strings.HasPrefix(lines[start-1], indent) && !strings.HasPrefix(lines[start-1], indent+" ") && strings.TrimSpace(lines[start-1]) != "" && !strings.HasSuffix(strings.TrimSpace(lines[start-1]), ":") {
		start--
	}
	for end < len(lines) && strings.HasPrefix(lines[end], indent) && strings.TrimSpace(lines[end]) != "" {
		end++
	}
	block := append([]string{}, lines[start:end]...)
	block = setKey(block, indent, "tag", strconv.Quote(tag))
	if digest != "" {
		block = setKey(block, indent, "digest", digest)
	}
	out := append(append(append([]string{}, lines[:start]...), block...), lines[end:]...)
	return []byte(strings.Join(out, "\n")), nil
}

// setKey replaces "key: value" inside an entry (keeping a trailing comment) or appends it.
func setKey(entry []string, indent, key, value string) []string {
	for i, l := range entry {
		if strings.HasPrefix(strings.TrimSpace(l), key+":") {
			comment := ""
			if j := strings.Index(l, " #"); j >= 0 {
				comment = l[j:]
			}
			entry[i] = indent + key + ": " + value + comment
			return entry
		}
	}
	return append(entry, indent+key+": "+value)
}

// Policy is the latest image an ImagePolicy selected, e.g. ghcr.io/acme/shop-app:2.8.2.
type Policy struct {
	Repository string
	Tag        string
	Digest     string // optional
}

// Change is one rewritten line.
type Change struct {
	Line     int
	Marker   string
	Old, New string
}

var markerRE = regexp.MustCompile(`#\s*(\{"\$imagepolicy":\s*"[^"]+"\})\s*$`)

// ApplySetters rewrites every value that carries an $imagepolicy marker. policies is keyed
// by "<namespace>:<name>". Marker suffixes: none = full reference, ":tag", ":name",
// ":digest". A marker naming an unknown policy is an error: the automation would silently
// never update that field.
func ApplySetters(src []byte, policies map[string]Policy) ([]byte, []Change, error) {
	lines := strings.Split(string(src), "\n")
	var changes []Change
	for i, l := range lines {
		m := markerRE.FindStringSubmatchIndex(l)
		if m == nil {
			continue
		}
		var marker struct {
			Ref string `json:"$imagepolicy"`
		}
		if err := json.Unmarshal([]byte(l[m[2]:m[3]]), &marker); err != nil {
			return nil, nil, fmt.Errorf("line %d: %w", i+1, err)
		}
		parts := strings.Split(marker.Ref, ":")
		if len(parts) < 2 || len(parts) > 3 {
			return nil, nil, fmt.Errorf("line %d: marker %q is not <ns>:<name>[:field]", i+1, marker.Ref)
		}
		p, ok := policies[parts[0]+":"+parts[1]]
		if !ok {
			return nil, nil, fmt.Errorf("line %d: no ImagePolicy %s:%s", i+1, parts[0], parts[1])
		}
		field := ""
		if len(parts) == 3 {
			field = parts[2]
		}
		var val string
		switch field {
		case "":
			val = p.Repository + ":" + p.Tag
		case "tag":
			val = p.Tag
		case "name":
			val = p.Repository
		case "digest":
			val = p.Digest
		default:
			return nil, nil, fmt.Errorf("line %d: unknown marker field %q", i+1, field)
		}
		head := strings.TrimRight(l[:m[0]], " ")
		colon := strings.Index(head, ": ")
		if colon < 0 {
			return nil, nil, fmt.Errorf("line %d: marker not on a key: value line", i+1)
		}
		old := strings.TrimSpace(head[colon+2:])
		quoted := strings.HasPrefix(old, "\"")
		bare := strings.Trim(old, "\"")
		if bare == val {
			continue
		}
		nv := val
		if quoted {
			nv = strconv.Quote(val)
		}
		lines[i] = head[:colon+2] + nv + " " + l[m[0]:]
		changes = append(changes, Change{Line: i + 1, Marker: marker.Ref, Old: bare, New: val})
	}
	return []byte(strings.Join(lines, "\n")), changes, nil
}

type semver struct{ major, minor, patch int }

func parse(s string) (semver, bool) {
	s = strings.TrimPrefix(s, "v")
	f := strings.Split(s, ".")
	if len(f) != 3 {
		return semver{}, false
	}
	var v [3]int
	for i, x := range f {
		n, err := strconv.Atoi(x)
		if err != nil || n < 0 {
			return semver{}, false // pre-releases (1.2.3-rc.1) and junk are skipped
		}
		v[i] = n
	}
	return semver{v[0], v[1], v[2]}, true
}

func (a semver) less(b semver) bool {
	if a.major != b.major {
		return a.major < b.major
	}
	if a.minor != b.minor {
		return a.minor < b.minor
	}
	return a.patch < b.patch
}

// Newest returns the highest release tag that matches pattern (nil = all tags) and lies in
// [min, maxExclusive). ok is false when nothing qualifies: the policy keeps its old value.
func Newest(tags []string, pattern *regexp.Regexp, min, maxExclusive string) (tag string, ok bool) {
	lo, ok1 := parse(min)
	hi, ok2 := parse(maxExclusive)
	if !ok1 || !ok2 {
		return "", false
	}
	var best semver
	for _, t := range tags {
		if pattern != nil && !pattern.MatchString(t) {
			continue
		}
		v, ok := parse(t)
		if !ok || v.less(lo) || !v.less(hi) {
			continue
		}
		if tag == "" || best.less(v) {
			best, tag = v, t
		}
	}
	return tag, tag != ""
}
go
package imagebump

import (
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"testing"

	"academy/gitops-argocd-flux/repocheck"
)

// repoFile resolves a path inside the config repository in either layout (this
// knowledge base, or the real repository with the module in tools/).
func repoFile(t *testing.T, rel string) string {
	t.Helper()
	root, err := repocheck.FindRoot(".")
	if err != nil {
		t.Fatal(err)
	}
	return filepath.Join(root, rel)
}

func TestBumpPromotionKeepsComments(t *testing.T) {
	src, err := os.ReadFile(repoFile(t, "apps/orders-api/overlays/prod/kustomization.yaml"))
	if err != nil {
		t.Fatal(err)
	}
	out, err := Bump(src, "ghcr.io/acme/orders-api", "1.5.0", "sha256:1111111111111111111111111111111111111111111111111111111111111111")
	if err != nil {
		t.Fatal(err)
	}
	s := string(out)
	for _, want := range []string{
		`    newTag: "1.5.0"`,
		`    digest: sha256:1111111111111111111111111111111111111111111111111111111111111111`,
		"# placeholder digest; the promotion PR writes the digest CI printed for 1.4.2",
		"namespace: shop-prod",
	} {
		if !strings.Contains(s, want) {
			t.Errorf("missing %q in:\n%s", want, s)
		}
	}
	// exactly two lines differ: a reviewable one-entry PR
	a, b := strings.Split(string(src), "\n"), strings.Split(s, "\n")
	if len(a) != len(b) {
		t.Fatalf("line count changed %d -> %d", len(a), len(b))
	}
	diff := 0
	for i := range a {
		if a[i] != b[i] {
			diff++
		}
	}
	if diff != 2 {
		t.Errorf("want 2 changed lines, got %d", diff)
	}
}

func TestBumpUnknownImage(t *testing.T) {
	src, _ := os.ReadFile(repoFile(t, "apps/orders-api/overlays/prod/kustomization.yaml"))
	if _, err := Bump(src, "ghcr.io/acme/nope", "1.0.0", ""); err == nil {
		t.Error("want error for an image that is not in the overlay")
	}
}

func TestBumpAddsMissingKey(t *testing.T) {
	src := []byte("images:\n  - name: ghcr.io/acme/x\n    newName: ghcr.io/acme/y\nreplicas: []\n")
	out, err := Bump(src, "ghcr.io/acme/x", "2.0.0", "")
	if err != nil {
		t.Fatal(err)
	}
	want := "images:\n  - name: ghcr.io/acme/x\n    newName: ghcr.io/acme/y\n    newTag: \"2.0.0\"\nreplicas: []\n"
	if string(out) != want {
		t.Errorf("got\n%s", out)
	}
}

// One ImagePolicy owns both Laravel images, so both lines move in the same commit.
func TestApplySettersOnLaravelOverlay(t *testing.T) {
	src, err := os.ReadFile(repoFile(t, "apps/shop-laravel/overlays/staging/kustomization.yaml"))
	if err != nil {
		t.Fatal(err)
	}
	pol := map[string]Policy{"flux-system:shop-laravel": {Repository: "ghcr.io/acme/shop-app", Tag: "2.9.0"}}
	out, ch, err := ApplySetters(src, pol)
	if err != nil {
		t.Fatal(err)
	}
	if len(ch) != 2 {
		t.Fatalf("want both images bumped together, got %+v", ch)
	}
	for _, c := range ch {
		if c.Old != "2.8.1" || c.New != "2.9.0" || c.Marker != "flux-system:shop-laravel:tag" {
			t.Errorf("unexpected change %+v", c)
		}
	}
	if got := strings.Count(string(out), `newTag: "2.9.0" # {"$imagepolicy": "flux-system:shop-laravel:tag"}`); got != 2 {
		t.Errorf("want 2 rewritten lines with marker kept, got %d:\n%s", got, out)
	}
	if _, ch2, _ := ApplySetters(out, pol); len(ch2) != 0 {
		t.Errorf("second run changed %v", ch2)
	}
}

func TestBumpHelmImageOnHelmRelease(t *testing.T) {
	src, err := os.ReadFile(repoFile(t, "clusters/prod/helmrelease-orders-api.yaml"))
	if err != nil {
		t.Fatal(err)
	}
	d := "sha256:2222222222222222222222222222222222222222222222222222222222222222"
	out, err := BumpHelmImage(src, "ghcr.io/acme/orders-api", "1.5.0", d)
	if err != nil {
		t.Fatal(err)
	}
	s := string(out)
	for _, want := range []string{`      tag: "1.5.0"`, "      digest: " + d, "# the promote-to-prod workflow bumps tag and digest here", "driftDetection:"} {
		if !strings.Contains(s, want) {
			t.Errorf("missing %q in:\n%s", want, s)
		}
	}
	if strings.Count(s, "\n") != strings.Count(string(src), "\n") {
		t.Error("line count changed")
	}
	if _, err := BumpHelmImage(src, "ghcr.io/acme/nope", "1", ""); err == nil {
		t.Error("want error for an unknown repository")
	}
}

func TestApplySettersFields(t *testing.T) {
	src := []byte(strings.Join([]string{
		`image: ghcr.io/acme/shop-app:2.0.0 # {"$imagepolicy": "flux-system:shop-app"}`,
		`repository: old/name # {"$imagepolicy": "flux-system:shop-app:name"}`,
		`tag: 2.0.0 # {"$imagepolicy": "flux-system:shop-app:tag"}`,
	}, "\n"))
	out, ch, err := ApplySetters(src, map[string]Policy{"flux-system:shop-app": {Repository: "ghcr.io/acme/shop-app", Tag: "2.1.0"}})
	if err != nil || len(ch) != 3 {
		t.Fatalf("err=%v changes=%v", err, ch)
	}
	want := strings.Join([]string{
		`image: ghcr.io/acme/shop-app:2.1.0 # {"$imagepolicy": "flux-system:shop-app"}`,
		`repository: ghcr.io/acme/shop-app # {"$imagepolicy": "flux-system:shop-app:name"}`,
		`tag: 2.1.0 # {"$imagepolicy": "flux-system:shop-app:tag"}`,
	}, "\n")
	if string(out) != want {
		t.Errorf("got\n%s", out)
	}
	if _, _, err := ApplySetters(src, map[string]Policy{}); err == nil {
		t.Error("a marker naming an unknown policy must be an error")
	}
}

func TestNewest(t *testing.T) {
	tags := []string{"2.7.0", "2.8.1", "2.10.0", "3.0.0", "2.11.0-rc.1", "sha-4f2a9c1", "latest", "1.9.9"}
	release := regexp.MustCompile(`^[0-9]+\.[0-9]+\.[0-9]+$`)
	if got, ok := Newest(tags, release, "2.0.0", "3.0.0"); !ok || got != "2.10.0" {
		t.Errorf(">=2.0.0 <3.0.0: got %q (numeric, not alphabetical: 2.10.0 > 2.8.1)", got)
	}
	if got, ok := Newest(tags, release, "2.8.0", "2.9.0"); !ok || got != "2.8.1" {
		t.Errorf("2.8.x: got %q", got)
	}
	if _, ok := Newest(tags, release, "4.0.0", "5.0.0"); ok {
		t.Error("nothing in range must keep the old value")
	}
}
go
// Command imagebump sets the tag (and digest) of one image, in place, keeping comments:
// in a kustomization.yaml images: entry (-format kustomize, the default) or in a
// HelmRelease values block that holds "repository: <image>" (-format helm). The
// promote-to-prod workflow runs it on every file that names the prod version.
//
//	imagebump -file apps/orders-api/overlays/prod/kustomization.yaml \
//	  -image ghcr.io/acme/orders-api -tag 1.5.0 -digest sha256:...
//	imagebump -format helm -file clusters/prod/helmrelease-orders-api.yaml \
//	  -image ghcr.io/acme/orders-api -tag 1.5.0 -digest sha256:...
package main

import (
	"flag"
	"fmt"
	"os"
	"regexp"

	"academy/gitops-argocd-flux/imagebump"
)

var digestRE = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`)

func main() {
	file := flag.String("file", "", "kustomization.yaml to edit")
	image := flag.String("image", "", "images[].name to change")
	tag := flag.String("tag", "", "new tag")
	digest := flag.String("digest", "", "new digest (sha256:<64 hex>), optional")
	format := flag.String("format", "kustomize", "kustomize (images: entry) or helm (values image block)")
	flag.Parse()
	if *file == "" || *image == "" || *tag == "" {
		flag.Usage()
		os.Exit(2)
	}
	if *digest != "" && !digestRE.MatchString(*digest) {
		fmt.Fprintf(os.Stderr, "digest %q is not sha256:<64 hex>\n", *digest)
		os.Exit(2)
	}
	src, err := os.ReadFile(*file)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	var out []byte
	switch *format {
	case "kustomize":
		out, err = imagebump.Bump(src, *image, *tag, *digest)
	case "helm":
		out, err = imagebump.BumpHelmImage(src, *image, *tag, *digest)
	default:
		err = fmt.Errorf("unknown -format %q", *format)
	}
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	if err := os.WriteFile(*file, out, 0o644); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	fmt.Printf("%s: %s -> %s %s\n", *file, *image, *tag, *digest)
}

۳. تست سیاست Repository. تمام سندهای YAML باید Parse شوند؛ Application و ApplicationSet نباید Project با نام default یا Project قالبی داشته باشند؛ فقط Project با نام platform می‌تواند argocd را هدف بگیرد؛ Annotationهای Hook باید فاز معتبر داشته باشند؛ هر Kustomization این repo باید prune و path موجود داشته باشد؛ هر dependsOn باید پیدا شود؛ هر نشانگر باید ImagePolicy موجود را نام ببرد؛ نشانگر Prod فقط توسط Automation با Push به شاخهٔ جدا نوشته شود؛ Tag عملیاتی بدون نشانگر باید Digest داشته باشد.

go
// Package repocheck loads a GitOps config repository and checks the rules a reviewer
// would otherwise have to remember. Its tests run in the config repo's CI on every pull
// request, before any agent sees the change.
package repocheck

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"io/fs"
	"os"
	"path/filepath"
	"regexp"
	"strings"

	"gopkg.in/yaml.v3"
)

// Doc is one YAML document with the file it came from.
type Doc struct {
	File string
	Obj  map[string]any
}

// Kind returns apiVersion group + kind, e.g. "kustomize.toolkit.fluxcd.io/Kustomization".
func (d Doc) Kind() string {
	api, _ := d.Obj["apiVersion"].(string)
	kind, _ := d.Obj["kind"].(string)
	if i := strings.Index(api, "/"); i >= 0 {
		api = api[:i]
	}
	return api + "/" + kind
}

// Name returns metadata.namespace/metadata.name.
func (d Doc) Name() string {
	return Str(d.Obj, "metadata", "namespace") + "/" + Str(d.Obj, "metadata", "name")
}

// Str walks nested maps and returns the string at the end ("" if absent).
func Str(m map[string]any, path ...string) string {
	v := Get(m, path...)
	s, _ := v.(string)
	return s
}

// Get walks nested maps.
func Get(m map[string]any, path ...string) any {
	var cur any = m
	for _, p := range path {
		mm, ok := cur.(map[string]any)
		if !ok {
			return nil
		}
		cur = mm[p]
	}
	return cur
}

// Load parses every .yaml/.yml file under root (all documents). A parse error is fatal:
// an agent that cannot parse the repository deploys nothing.
func Load(root string) ([]Doc, error) {
	var docs []Doc
	err := filepath.WalkDir(root, func(path string, e fs.DirEntry, err error) error {
		if err != nil {
			return err
		}
		if e.IsDir() || !(strings.HasSuffix(path, ".yaml") || strings.HasSuffix(path, ".yml")) {
			return nil
		}
		b, err := os.ReadFile(path)
		if err != nil {
			return err
		}
		rel, _ := filepath.Rel(root, path)
		dec := yaml.NewDecoder(bytes.NewReader(b))
		for i := 1; ; i++ {
			var o map[string]any
			err := dec.Decode(&o)
			if errors.Is(err, io.EOF) {
				break
			}
			if err != nil {
				return fmt.Errorf("%s document %d: %w", rel, i, err)
			}
			if len(o) > 0 {
				docs = append(docs, Doc{File: rel, Obj: o})
			}
		}
		return nil
	})
	return docs, err
}

var markerRE = regexp.MustCompile(`\{"\$imagepolicy":\s*"([^":]+):([^":]+)(:[a-z]+)?"\}`)

// Marker is one Flux setter marker found in a file.
type Marker struct {
	File, Policy string // Policy is "<namespace>/<name>"
}

// Markers finds every $imagepolicy marker under root.
func Markers(root string) ([]Marker, error) {
	var out []Marker
	err := filepath.WalkDir(root, func(path string, e fs.DirEntry, err error) error {
		if err != nil || e.IsDir() || !strings.HasSuffix(path, ".yaml") {
			return err
		}
		b, err := os.ReadFile(path)
		if err != nil {
			return err
		}
		rel, _ := filepath.Rel(root, path)
		for _, m := range markerRE.FindAllSubmatch(b, -1) {
			out = append(out, Marker{File: rel, Policy: string(m[1]) + "/" + string(m[2])})
		}
		return nil
	})
	return out, err
}
go
package repocheck

import (
	"os"
	"path/filepath"
	"strings"
	"testing"
)

// root is the config repository: REPO_ROOT, or found from this package's directory in
// either layout (tools/repocheck in the real repo, go/repocheck in this knowledge base).
var root = func() string {
	r, err := FindRoot(".")
	if err != nil {
		panic(err)
	}
	return r
}()

func docs(t *testing.T) []Doc {
	t.Helper()
	d, err := Load(root)
	if err != nil {
		t.Fatal(err)
	}
	if len(d) < 30 {
		t.Fatalf("only %d documents loaded", len(d))
	}
	return d
}

func TestEveryYAMLFileParses(t *testing.T) {
	docs(t)
	wf := FindWorkflows(root)
	if wf == "" {
		t.Fatal("no workflow directory found")
	}
	if _, err := Load(wf); err != nil {
		t.Fatal(err)
	}
}

// Argo CD: nothing deploys through the wide-open "default" project, and only the
// admin-level "platform" project may target the argocd namespace.
func TestArgoProjects(t *testing.T) {
	projects := map[string]bool{}
	for _, d := range docs(t) {
		if d.Kind() == "argoproj.io/AppProject" {
			name := Str(d.Obj, "metadata", "name")
			projects[name] = true
			dests, _ := Get(d.Obj, "spec", "destinations").([]any)
			for _, x := range dests {
				ns, _ := x.(map[string]any)["namespace"].(string)
				if ns == "argocd" && name != "platform" {
					t.Errorf("%s: project %s may deploy into argocd (admin-level)", d.File, name)
				}
			}
		}
	}
	for _, d := range docs(t) {
		var project string
		switch d.Kind() {
		case "argoproj.io/Application":
			project = Str(d.Obj, "spec", "project")
		case "argoproj.io/ApplicationSet":
			project = Str(d.Obj, "spec", "template", "spec", "project")
		default:
			continue
		}
		if project == "" || project == "default" || strings.Contains(project, "{{") {
			t.Errorf("%s %s: project %q (empty, default or templated)", d.File, d.Name(), project)
		} else if !projects[project] {
			t.Errorf("%s %s: project %q is not defined in the repo", d.File, d.Name(), project)
		}
	}
}

// Argo CD hook annotations must use a phase Argo CD knows; a typo silently makes the
// Job a normal resource that runs in parallel with the rollout.
func TestArgoHookPhases(t *testing.T) {
	valid := map[string]bool{"PreSync": true, "Sync": true, "Skip": true, "PostSync": true,
		"SyncFail": true, "PreDelete": true, "PostDelete": true}
	for _, d := range docs(t) {
		h := Str(d.Obj, "metadata", "annotations", "argocd.argoproj.io/hook")
		for _, p := range strings.Split(h, ",") {
			if h != "" && !valid[strings.TrimSpace(p)] {
				t.Errorf("%s: unknown hook phase %q", d.File, p)
			}
		}
	}
}

// Flux: every Kustomization that reads this repository points at a directory that exists
// and states prune explicitly (it is a required field).
func TestFluxKustomizationPaths(t *testing.T) {
	ours := map[string]bool{"flux-system": true, "shop-config": true}
	n := 0
	for _, d := range docs(t) {
		if d.Kind() != "kustomize.toolkit.fluxcd.io/Kustomization" {
			continue
		}
		if _, ok := Get(d.Obj, "spec", "prune").(bool); !ok {
			t.Errorf("%s %s: spec.prune must be set", d.File, d.Name())
		}
		if !ours[Str(d.Obj, "spec", "sourceRef", "name")] {
			continue // a tenant's own repository
		}
		p := Str(d.Obj, "spec", "path")
		if fi, err := os.Stat(filepath.Join(root, p)); err != nil || !fi.IsDir() {
			t.Errorf("%s %s: path %q does not exist", d.File, d.Name(), p)
		}
		n++
	}
	if n < 5 {
		t.Errorf("only %d Kustomizations checked", n)
	}
}

// Flux: every dependsOn names a Kustomization defined in the same cluster directory.
func TestFluxDependsOn(t *testing.T) {
	byDir := map[string]map[string]bool{}
	all := docs(t)
	for _, d := range all {
		if d.Kind() == "kustomize.toolkit.fluxcd.io/Kustomization" {
			dir := filepath.Dir(d.File)
			if byDir[dir] == nil {
				byDir[dir] = map[string]bool{}
			}
			byDir[dir][Str(d.Obj, "metadata", "name")] = true
		}
	}
	for _, d := range all {
		deps, _ := Get(d.Obj, "spec", "dependsOn").([]any)
		for _, x := range deps {
			name, _ := x.(map[string]any)["name"].(string)
			if !byDir[filepath.Dir(d.File)][name] {
				t.Errorf("%s %s: dependsOn %q not defined in %s", d.File, d.Name(), name, filepath.Dir(d.File))
			}
		}
	}
}

// Image automation: every setter marker names an existing ImagePolicy, and a marker in a
// prod overlay is only updated by an automation that pushes to a separate branch (a PR).
// Prod images without a marker must pin a digest.
func TestImageAutomationRules(t *testing.T) {
	policies := map[string]bool{}
	type iua struct{ path, checkout, push string }
	var autos []iua
	for _, d := range docs(t) {
		switch d.Kind() {
		case "image.toolkit.fluxcd.io/ImagePolicy":
			policies[d.Name()] = true
		case "image.toolkit.fluxcd.io/ImageUpdateAutomation":
			autos = append(autos, iua{
				path:     filepath.Clean(Str(d.Obj, "spec", "update", "path")),
				checkout: Str(d.Obj, "spec", "git", "checkout", "ref", "branch"),
				push:     Str(d.Obj, "spec", "git", "push", "branch"),
			})
		}
	}
	ms, err := Markers(root)
	if err != nil {
		t.Fatal(err)
	}
	if len(ms) == 0 {
		t.Fatal("no markers found")
	}
	for _, m := range ms {
		if !policies[m.Policy] {
			t.Errorf("%s: marker names unknown ImagePolicy %s", m.File, m.Policy)
		}
		if !strings.Contains(m.File, "/prod/") {
			continue
		}
		covered := false
		for _, a := range autos {
			if strings.HasPrefix(m.File, a.path+"/") {
				covered = true
				if a.push == "" || a.push == a.checkout {
					t.Errorf("%s: prod marker updated by an automation that pushes straight to %s", m.File, a.checkout)
				}
			}
		}
		if !covered {
			t.Errorf("%s: prod marker not covered by any ImageUpdateAutomation", m.File)
		}
	}
	// prod overlays: an image entry needs a digest or a marker
	files, _ := filepath.Glob(filepath.Join(root, "apps/*/overlays/prod/kustomization.yaml"))
	for _, f := range files {
		b, _ := os.ReadFile(f)
		for _, l := range strings.Split(string(b), "\n") {
			if strings.HasPrefix(strings.TrimSpace(l), "newTag:") && !strings.Contains(l, "$imagepolicy") &&
				!strings.Contains(string(b), "digest: sha256:") {
				t.Errorf("%s: prod tag without digest or automation marker", f)
			}
		}
	}
}

// FindRoot must work in both layouts and honour REPO_ROOT.
func TestFindRootLayouts(t *testing.T) {
	t.Setenv("REPO_ROOT", "") // the layout cases below must not inherit the caller's REPO_ROOT
	real := t.TempDir()       // real config repo: apps/ at the top, module in tools/
	for _, d := range []string{"apps", "tools/repocheck", ".github/workflows"} {
		if err := os.MkdirAll(filepath.Join(real, d), 0o755); err != nil {
			t.Fatal(err)
		}
	}
	got, err := FindRoot(filepath.Join(real, "tools", "repocheck"))
	if err != nil || got != filepath.Clean(real) {
		t.Errorf("real layout: got %q, %v", got, err)
	}
	if wf := FindWorkflows(got); wf != filepath.Join(real, ".github", "workflows") {
		t.Errorf("real layout workflows: %q", wf)
	}
	kb := t.TempDir() // this knowledge base: config-repo/ and ci/ next to go/
	for _, d := range []string{"config-repo/apps", "go/repocheck", "ci"} {
		if err := os.MkdirAll(filepath.Join(kb, d), 0o755); err != nil {
			t.Fatal(err)
		}
	}
	got, err = FindRoot(filepath.Join(kb, "go", "repocheck"))
	if err != nil || got != filepath.Join(kb, "config-repo") {
		t.Errorf("kb layout: got %q, %v", got, err)
	}
	if wf := FindWorkflows(got); filepath.Clean(wf) != filepath.Join(kb, "ci") {
		t.Errorf("kb layout workflows: %q", wf)
	}
	t.Setenv("REPO_ROOT", real)
	if got, err := FindRoot("/nonexistent"); err != nil || got != real {
		t.Errorf("REPO_ROOT: got %q, %v", got, err)
	}
	t.Setenv("REPO_ROOT", filepath.Join(kb, "go"))
	if _, err := FindRoot("."); err == nil {
		t.Error("REPO_ROOT without apps/ must be an error")
	}
}
text
module academy/gitops-argocd-flux

go 1.24

require gopkg.in/yaml.v3 v3.0.1

CI مربوط به Config repository که این تست‌ها را اجرا و OCI artifact امضاشده منتشر می‌کند:

yaml
# Config repository CI. Pull requests: render every overlay and run the repository
# policy tests; nothing touches a cluster. Pushes to main: publish the repository as a
# signed OCI artifact and move the "prod" tag that prod clusters pull. The approval gate
# is the reviewed PR that changed overlays/prod; the tag only says "this commit is
# published". During a change freeze, stop moving the tag (skip this job).
name: config-repo
on:
  pull_request:
  push:
    branches: [main]
permissions:
  contents: read
jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-go@v7
        with:
          go-version-file: tools/go.mod
      # every overlay must build; a broken overlay would make the agent report a
      # build error instead of deploying
      - name: Render all overlays
        run: |
          set -euo pipefail
          for k in $(find apps infrastructure -name kustomization.yaml); do
            dir=$(dirname "$k")
            echo "::group::$dir"
            kubectl kustomize "$dir" > /dev/null
            echo "::endgroup::"
          done
      # repository policy: YAML parses, every Flux path exists, no Application uses the
      # default project, prod overlays pin a digest, markers name a real ImagePolicy
      - name: Repository policy tests
        working-directory: tools
        run: go test ./...
  publish:
    if: github.event_name == 'push'
    needs: validate
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write # push to ghcr.io
      id-token: write # keyless cosign signing with the workflow's OIDC identity
    env:
      OCI_REPO: oci://ghcr.io/acme/shop-config
    steps:
      - uses: actions/checkout@v7
      - uses: fluxcd/flux2/action@main
        with:
          version: '2.10.1'
      - uses: sigstore/cosign-installer@v4.1.4
      - uses: docker/login-action@v4
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - name: Push, sign and tag for prod clusters
        run: |
          set -euo pipefail
          digest_url=$(flux push artifact "$OCI_REPO:$(git rev-parse --short HEAD)" \
            --path="." \
            --source="$(git config --get remote.origin.url)" \
            --revision="main@sha1:$(git rev-parse HEAD)" \
            --output=json | jq -r '.repository + "@" + .digest')
          cosign sign --yes "$digest_url"
          flux tag artifact "$OCI_REPO:$(git rev-parse --short HEAD)" --tag prod

سرویس Go همان‌طور که Argo CD در Git می‌بیند؛ Application آن همان orders-api-prod بالاست و این‌ها Overlayهایی هستند که رندر می‌کند:

yaml
# orders-api base: environment-neutral. Overlays reference this directory; it never knows them.
# Packaging details (labels, generators, components) are taught in the Helm/Kustomize chapter.
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
  - deployment.yaml
  - service.yaml
labels:
  - pairs:
      app.kubernetes.io/name: orders-api
      app.kubernetes.io/part-of: shop
    includeSelectors: true
images:
  - name: orders-api
    newName: ghcr.io/acme/orders-api
    newTag: "1.4.2"
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: orders-api
spec:
  # no "replicas:" here: an HPA owns the count in prod, and a GitOps agent would
  # otherwise fight it on every reconcile (the "leave room for imperativeness" rule)
  selector:
    matchLabels: {}
  template:
    metadata:
      labels: {}
    spec:
      automountServiceAccountToken: false
      terminationGracePeriodSeconds: 30
      securityContext:
        runAsNonRoot: true
        runAsUser: 65532
        runAsGroup: 65532
      containers:
        - name: orders-api
          image: orders-api
          ports:
            - name: http
              containerPort: 8080
          # Argo CD marks the Deployment Healthy and Flux's health check passes only when
          # the rollout completes, which needs these probes to go green
          readinessProbe:
            httpGet:
              path: /readyz
              port: http
          livenessProbe:
            httpGet:
              path: /healthz
              port: http
          resources:
            requests:
              cpu: 100m
              memory: 64Mi
            limits:
              memory: 128Mi
yaml
# staging: tracks the newest 1.x build. Argo CD Image Updater commits the tag here
# (writeBackTarget: kustomization), exactly as "kustomize edit set image" would.
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: shop-staging
resources:
  - ../../base
labels:
  - pairs:
      app.kubernetes.io/environment: staging
images:
  - name: ghcr.io/acme/orders-api
    newTag: "1.5.0"
replicas:
  - name: orders-api
    count: 1
yaml
# prod: changed only by a reviewed pull request (the promotion PR copies the tag that
# passed staging). The digest pins the exact bytes; the tag stays for humans.
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: shop-prod
resources:
  - ../../base
labels:
  - pairs:
      app.kubernetes.io/environment: prod
images:
  - name: ghcr.io/acme/orders-api
    newTag: "1.4.2"
    # placeholder digest; the promotion PR writes the digest CI printed for 1.4.2
    digest: sha256:0b7e2a3c5d9f41e6a8b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3

نگاه Go (The Go angle) ​

  • هر دو Agent برنامهٔ Go با کتابخانه‌های مشترک‌اند. Argo CD و Flux از client-go و Reconciler به‌سبک controller-runtime استفاده می‌کنند. Flux، API کنترل‌گرها را با Go moduleهای github.com/fluxcd/* منتشر می‌کند و Typeهای Application در Repository خود Argo CD هستند. این فصل عمداً آن‌ها را Import نمی‌کند؛ ابزارها با go 1.24 و یک وابستگی می‌مانند و شکل YAML با تست کنترل می‌شود.
  • Readiness تعیین‌کنندهٔ Health است. وقتی Replica به‌روزشده با مطلوب برابر شود، Argo CD به Deployment وضعیت Healthy می‌دهد؛ این فقط با سبزشدن /readyz رخ می‌دهد. پیش از srv.Shutdown، Readiness را خاموش کنید تا Pod قدیمی پیش از توقف از Endpoint خارج شود؛ در سرویس فصل Image نشان داده شده است.
  • نسخه را قابل مشاهده کنید. با -ldflags "-X main.version=..." نسخه را درج و در /version ارائه کنید. پس از Sync، curl /version ارزان‌ترین شاهد اجرای همان چیزی است که Git می‌گوید.
  • نوشتن Reconciler خودتان. حلقهٔ سازوکار همان الگوی Operator است؛ ساخت آن در Go با controller-runtime در گسترش Kubernetes آمده است.
  • تست Manifest در Go. کتابخانهٔ yaml.v3 جریان چندسندی را با Decoder.Decode تا io.EOF Decode می‌کند. مقصد map[string]any باشد؛ Map type نام‌دار همهٔ Mapهای تودرتو را هم همان Type می‌کند؛ اولین اجرای تست مدل Drift این خطا را گرفت.
  • Image automation برای Go با Tagهای semver تغییرناپذیر حاصل از git tag و Tag جدا با پیشوند sha- برای ردیابی بهتر کار می‌کند؛ filterTags سیاست را به انتشارها محدود می‌کند.

Laravel ​

قبل (Before) ​

اسکریپت استقرار Laravel از CI روی Production، رایج در روش Push:

bash
# Before: SSH/kubectl deploy from CI; ordering lives in a script, not in the desired state
kubectl -n shop-prod set image deploy/shop-web php-fpm=ghcr.io/acme/shop-app:latest
kubectl -n shop-prod exec deploy/shop-web -c php-fpm -- php artisan migrate --force   # runs in a serving pod
kubectl -n shop-prod rollout status deploy/shop-web || echo "ignore, it usually works"
# no smoke test, no record in Git of what runs, worker Deployment forgotten

بعد (After) ​

برنامهٔ Laravel دو Deployment دارد: وب با php-fpm و Nginx و Worker با queue:work، به‌علاوهٔ Jobهای انتشار. Kustomization مربوط به Laravel در Flux یا ApplicationSet در Argo CD آن را تحویل می‌دهد. Migration در هر انتشار یک‌بار، به‌شکل PreSync hook در Argo CD یا Job اجباری که Kustomization منتظرش می‌ماند در Flux اجرا می‌شود؛ --isolated مانع Migration هم‌زمان دو اجراست. Smoke test زیر Argo CD یک PostSync hook پس از Healthy شدن همه‌چیز است. Flux فاز ندارد؛ خود فرمان با Poll کردن /version در Web Service تا رسیدن به نسخهٔ Image خود Job، ترتیب را برقرار می‌کند و بعد پایگاه داده، Schema جدید و Cache را می‌سنجد.

yaml
# shop-laravel base: one app image (php-fpm) runs as web and worker; Nginx fronts php-fpm
# inside the web pod. Image build details: the Images & Dockerfiles chapter.
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
  - web.yaml
  - worker.yaml
  - service.yaml
labels:
  - pairs:
      app.kubernetes.io/part-of: shop-laravel
images:
  # containers name the real repository without a tag; each overlay sets the tag
  - name: ghcr.io/acme/shop-app
    newTag: "2.7.0"
  - name: ghcr.io/acme/shop-web
    newTag: "2.7.0"
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: shop-web
  labels:
    app.kubernetes.io/name: shop-web
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: shop-web
  template:
    metadata:
      labels:
        app.kubernetes.io/name: shop-web
    spec:
      containers:
        - name: php-fpm
          image: ghcr.io/acme/shop-app
          envFrom:
            # created outside Git (External Secrets Operator or a SOPS-decrypted Secret)
            - secretRef:
                name: shop-laravel-env
        - name: nginx
          image: ghcr.io/acme/shop-web
          ports:
            - name: http
              containerPort: 8080
          # Laravel's built-in health route; the rollout (and so the GitOps health
          # status) only completes when /up answers 200
          readinessProbe:
            httpGet:
              path: /up
              port: http
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: shop-worker
  labels:
    app.kubernetes.io/name: shop-worker
spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: shop-worker
  template:
    metadata:
      labels:
        app.kubernetes.io/name: shop-worker
    spec:
      terminationGracePeriodSeconds: 120
      containers:
        - name: worker
          image: ghcr.io/acme/shop-app
          command: ["php", "artisan", "queue:work", "--max-time=3600"]
          envFrom:
            - secretRef:
                name: shop-laravel-env
yaml
# Release jobs that run once per sync: migrations before, a smoke test after.
# Argo CD reads the hook annotations; Flux ignores them and applies the Jobs as normal
# objects (force: enabled recreates a Job whose immutable template changed).
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
  - migrate-job.yaml
  - smoke-job.yaml
yaml
# prod: the same markers, but the prod ImageUpdateAutomation pushes to a separate branch,
# so every bump arrives as a pull request that a human approves (promotion by PR).
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: shop-prod
resources:
  - ../../base
  - ../../release-jobs
labels:
  - pairs:
      app.kubernetes.io/environment: prod
images:
  - name: ghcr.io/acme/shop-app
    newTag: "2.7.0" # {"$imagepolicy": "flux-system:shop-laravel:tag"}
  - name: ghcr.io/acme/shop-web
    newTag: "2.7.0" # {"$imagepolicy": "flux-system:shop-laravel:tag"}
replicas:
  - name: shop-web
    count: 3
  - name: shop-worker
    count: 2

Smoke test به‌شکل فرمان Artisan با APIهای مستند Laravel 13 یعنی DB::select، Schema::hasColumn، Cache::put / Cache::pull و Http::timeout(...)->get(...) در Clientِ HTTP؛ همراه Route با نام /version که Poll می‌شود. config('app.version') مقدار APP_VERSION تعبیه‌شده در Image را می‌خواند:

php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Schema;
use Throwable;

/**
 * Post-deploy smoke test.
 *
 * Argo CD runs it as a PostSync hook, i.e. after every resource is Healthy. Flux has no
 * hook phases: the Job starts in the same reconcile as the new Deployments, so the first
 * check waits (bounded) until the web Service answers /version with THIS image's
 * version, which proves new pods serve traffic. Only then are the dependency checks run.
 * A non-zero exit fails the Job: Argo CD marks the sync failed (on-sync-failed), Flux keeps
 * the Kustomization not Ready (wait: true) and the error Alert fires.
 */
class SmokeTest extends Command
{
    protected $signature = 'app:smoke-test
        {--url=http://shop-web : Base URL of the web Service inside the namespace}
        {--attempts=30 : Polls of /version before giving up}
        {--interval=5 : Seconds between polls}';

    protected $description = 'Verify the deployed release against its real dependencies';

    public function handle(): int
    {
        $expected = (string) config('app.version', 'unknown');

        if (! $this->waitForRelease($expected)) {
            $this->error("web: release {$expected} never served /version");

            return self::FAILURE;
        }

        $checks = [
            'database' => fn () => (int) DB::select('select 1 as ok')[0]->ok === 1,
            // the newest migration of this release; fails if the migrate Job did not run
            'schema' => fn () => Schema::hasColumn('orders', 'fulfilment_status'),
            'cache' => function () {
                $key = 'smoke:'.bin2hex(random_bytes(4));
                Cache::put($key, 'ok', 30);

                return Cache::pull($key) === 'ok';
            },
        ];

        $failed = 0;
        foreach ($checks as $name => $check) {
            try {
                $ok = (bool) $check();
            } catch (Throwable $e) {
                $ok = false;
                $this->error("{$name}: ".$e->getMessage());
            }
            $ok ? $this->info("{$name}: ok") : $this->error("{$name}: FAILED");
            $failed += $ok ? 0 : 1;
        }

        $this->line(sprintf('release %s: %d/%d checks passed', $expected, count($checks) - $failed, count($checks)));

        return $failed === 0 ? self::SUCCESS : self::FAILURE;
    }

    /**
     * Poll GET {url}/version until it reports the expected version. Old pods (previous
     * release) and pods that are not ready yet both count as "not yet".
     */
    private function waitForRelease(string $expected): bool
    {
        $url = rtrim((string) $this->option('url'), '/').'/version';
        for ($i = 1; $i <= (int) $this->option('attempts'); $i++) {
            try {
                $response = Http::timeout(3)->get($url);
                $seen = $response->successful() ? (string) $response->json('version') : 'HTTP '.$response->status();
            } catch (Throwable $e) {
                $seen = $e->getMessage();
            }
            if ($seen === $expected) {
                $this->info("web: {$url} serves {$expected} (attempt {$i})");

                return true;
            }
            $this->line("web: attempt {$i}: {$seen}");
            sleep((int) $this->option('interval'));
        }

        return false;
    }
}
php
<?php

// routes/web.php (excerpt): the version endpoint the smoke test polls. APP_VERSION is
// baked into the image at build time, so web pods and the smoke Job report the same
// value only when the new release is the one serving traffic.
use Illuminate\Support\Facades\Route;

Route::get('/version', function () {
    return ['version' => config('app.version')];
});

نگاه Laravel (The Laravel angle) ​

  • Migration مرحلهٔ انتشار است، نه شروع کانتینر. Laravel پیش از Migration مخرب در Production تأیید می‌خواهد: "To force the commands to run without a prompt, use the --force flag". در چند Cluster یا Sync تکراری، --isolated باعث می‌شود Laravel، "acquire an atomic lock using your application's cache driver before attempting to run your migrations". Cache باید مشترک باشد، مثلاً Redis.
  • Migration باید با گذشته سازگار باشد. در Argo CD، PreSync Job پیش از Pod تازه اجرا می‌شود. در Flux، Job مهاجرت، Smoke Job و Deploymentها در همان Reconciliation اعمال می‌شوند؛ backoffLimit: 4 در Smoke Job این رقابت را تحمل می‌کند. روش سخت‌گیرانه‌تر، Kustomization جدا برای Jobها با ترتیب dependsOn است. در هر دو، Pod قدیمی حین Rollout خدمت می‌دهد؛ پس ابتدا Expand، مثلاً ستون Nullable، و در انتشار بعد Contract. همین سازگاری Rollback با Revert را امن می‌کند.
  • Route سلامت. مسیر داخلی /up در Laravel، "will return a 200 HTTP response if the application has booted without exceptions". آن را Readiness probe کنید تا وضعیت Health عامل معنی داشته باشد.
  • پیکربندی. جای .env در Git نیست. Overlayها به Secret با نام shop-laravel-env ارجاع می‌دهند که SOPS در Flux یا ESO تأمین می‌کند. php artisan optimize باید در Entrypoint کانتینر اجرا شود، جایی که Environment واقعی موجود است؛ Image و Dockerfile.
  • Worker و Drift. فرمان queue:work --max-time=3600 هر ساعت خارج می‌شود و Kubernetes دوباره آن را اجرا می‌کند؛ این Drift نیست چون Pod spec عوض نمی‌شود. kubectl rollout restart، Annotation با نام restartedAt می‌افزاید که Flux حذف می‌کند، مگر با --field-manager=flux-client-side-apply اجرا شود.
  • Image automation برچسب Laravel در خودکارسازی تصویر Flux: CI روی shop-app و shop-web یک نسخهٔ انتشار می‌گذارد و ابتدا shop-web را Push می‌کند. یک ImagePolicy با نام shop-laravel روی Repository مربوط به shop-app از طریق نشانگر یکسان مالک هر دو خط Overlay است؛ هر دو Tag در یک Commit تغییر می‌کنند. دو سیاست مستقل چنین تضمینی ندارند.

حل مسئله‌های کلاسیک (Solving the classic problems) ​

مسئلهراه‌حلروشمزیتهزینه یا محدودیت
CI دسترسی cluster-admin داردAgent کششیArgo CD/Flux داخل Cluster؛ CI فقط در Git می‌نویسداعتبارنامهٔ Cluster بیرون نمی‌رودبهره‌برداری Agent
کسی نمی‌داند چه چیزی اجرا می‌شودGit به‌عنوان سابقهTag و Digest در Overlay و وضعیت Agentپاسخ با git logنظم و حذف مسیرهای فرعی
Hotfix دستی باقی می‌ماندSelf-heal و اصلاح DriftselfHeal: true؛ بازهٔ Fluxپیکربندی تک‌افتاده باقی نمی‌ماندرخداد نیازمند Suspend است
Manifest حذف می‌شود ولی منبع اجرا می‌ماندPruneprune: true و استثنای Prune=falseNamespace تمیزCommit بد ممکن است حذف کند؛ محافظ allowEmpty
Migration با Rollout رقابت می‌کندHook یا Job مرتبPreSync Job، --isolated، Expand/Contractیک اجرا در هر انتشارشکست Hook مانع Deploy
هر محیط چندین فایل YAML می‌خواهدApplicationSet یا پوشهٔ ClusterMatrix حاصل Git × Clusterبرنامهٔ تازه یعنی پوشهٔ تازهقالب فقط برای مدیر
Staging از انتشار عقب می‌ماندImage automationFlux ImageUpdateAutomation یا Image Updaterحذف تغییر دستی Tagربات با حق نوشتن Git
Prod نیازمند تأیید استPromotion با PRAutomation به شاخه یا PR از CIبازبینی همان سابقهٔ تغییرکندتر
Rollbackgit revertRevert کردن Commit ارتقاGit و Cluster هماهنگMigration داده برنمی‌گردد
تحویل کندWebhook/api/webhook در Argo CD، Receiver در Fluxدر حد ثانیهارائهٔ Endpoint وب‌هوک
Secrets در GitSOPS / Sealed Secrets / ESOSecretsبدون متن سادهمدیریت کلید
نوسان HPAIgnore یا حذف replicasignoreDifferences، driftDetection.ignoreپایداریباید برای هر فیلد رعایت شود

مهاجرت از Push به Pull بدون قطعی ​

Agent را با Automated sync خاموش نصب کنید، Application/Kustomization را به Manifest فعلی اشاره دهید و Diff را بخوانید؛ هر شیء OutOfSync تغییر دستی ثبت‌نشده را آشکار می‌کند. تغییرهای مطلوب را Commit کنید؛ سپس به‌ترتیب Automated sync، Prune و Self-heal را روشن کنید؛ هر بار یک محیط. کار Deploy در CI را آخر از همه حذف کنید.

محیط پیش‌نمایش برای هر Pull request ​

Pull request generator در Argo CD را با Project ثابت shop-previews به کار ببرید که مقصدهایش فقط Namespaceهای orders-api-pr-* را مجاز می‌دانند. Overlay پیش‌نمایش Namespace تعیین نکند؛ kustomize.namespace در Application همهٔ اشیا را در orders-api-pr-<number> قرار می‌دهد. رندر Overlay مربوط به Staging به‌جای آن شکست می‌خورد، چون destination.namespace، "will only be set for namespace-scoped resources that have not set a value for .metadata.namespace" و آن Overlay مقدار shop-staging دارد. CI، Imageهای pr-<short sha> را Push می‌کند و Application با بسته‌شدن PR حذف می‌شود. Flux، PR generator ندارد؛ تیم‌ها از CI برای هر PR قالب Kustomization می‌سازند یا ابزار جدا به کار می‌برند.

برنامه‌ای که پس از هر Sync باز هم OutOfSync است ​

فرمان argocd app diff را اجرا کنید؛ اینجا مورد انتظار است و اجرا نشده. فیلد را بررسی کنید: پیش‌فرض API server است و Manifest فیلد اضافی یا نامعتبر دارد؟ متعلق به Controller است و باید ignoreDifferences اضافه یا از Git حذف شود؟ Chart با randAlphaNum مقدار تصادفی می‌سازد؟ یا Argo CD می‌خواهد منبعی را Prune کند ولی Prune خاموش است؟

انتخاب (Choosing) ​

Argo CD یا Flux ​

وضعیتانتخابدلیل
تیم‌های متعدد UI، SSO و RBAC هر برنامه می‌خواهندArgo CDUI داخلی، Dex/OIDC، Casbin RBAC و AppProject
یک نمونهٔ مرکزی برای چند ClusterArgo CDمدل Hub با Cluster ثبت‌شده
هر Cluster مستقل و بدون نیاز به UIFluxAgent هر Cluster؛ فقط Kubernetes RBAC
استفادهٔ زیاد از Chart بیرونی با Hook و TestFlux؛ یا Argo CD با آگاهی از نگاشت Hookهاانتشار واقعی Helm و Remediation
Image automation بدون پروژهٔ اضافهFluxControllerها در همان Toolkit
Preview برای PRArgo CDPull request generator
Multi-tenancy سخت‌گیرانه در Cluster مشترکFluxاستفاده از هویت مستاجر و Flagهای محدودسازی
Pipeline ارتقا میان Stageهاهرکدام همراه Kargoهیچ‌کدام Promotion داخلی ندارد

چیدمان Repository ​

شکل تیمچیدمان
یک تیم و چند سرویسConfig repo به‌شکل Monorepo، Overlay هر محیط
تیم Platform و تیم‌های برنامهrepo هر تیم؛ repo مربوط به Platform مستاجرها را معرفی می‌کند
Prod مقررات‌محورrepo جدا برای محیط Prod
چند Cluster در هر محیطپوشه‌های clusters/<name>/ با Overlay مشترک apps/

Tag چگونه به Git می‌رسد ​

محیطسازوکار
dev / previewCI، Tag را با kustomize.images در Application یا PR generator تنظیم می‌کند
stagingImage automation به main، Commit می‌کند
prodPR ارتقا از ربات، Push شاخهٔ Flux، شاخهٔ Image Updater یا Kargo همراه Digest

در معماری: از یک پردازه تا سیستم توزیع‌شده (In architecture: from a single process to a distributed system) ​

GitOps مشخص می‌کند چه کسی مجاز به تغییر سیستم در حال اجراست و آن تغییر چگونه ثبت می‌شود. پرسش‌های معماری دربارهٔ تعداد Repositoryها، تعداد Agentها و منبع دریافت هر Cluster هستند.

یکپارچه (Monolith): یک برنامه، یک Cluster و یک Application ​

Laravel یکپارچه در یک Cluster: یک Config repo با apps/shop-laravel/overlays/{staging,prod}، یک نمونهٔ Argo CD یا Fluxِ Bootstrap‌شده در هر Cluster، Automated sync با Prune و Self-heal، Migration به‌شکل PreSync Job و PR ارتقا به Prod. حتی در این اندازه هم اصول برقرارند: اعتبارنامهٔ Cluster در CI نباشد، Readiness روی /up و Rollback با Revert.

یکپارچهٔ ماژولار (Modular monolith): یک repo و چند خروجی قابل استقرار ​

یک Codebase، وب، Worker و سرویس همراه Go تولید می‌کند. هرکدام زیر apps/ پوشه می‌گیرد؛ ApplicationSet یا Kustomizationها آن‌ها را می‌سازند. dependsOn یا Sync waves اجزای مشترک مثل Namespace، CRD و Operator پایگاه داده را پیش از برنامه‌ها قرار می‌دهد. شمارهٔ نسخهٔ مشترک میان خروجی‌ها، Promotion را در یک PR نگه می‌دارد.

ریزخدمت‌ها (Microservices): تیم‌های متعدد و برنامه‌های متعدد ​

بیست سرویس با Repository و تیم مستقل دارید. تیم Platform مالک clusters/، infrastructure/ و argocd/ یا tenants/ در Config repository است؛ هر تیم با CODEOWNERS مالک apps/<service>/ یا مالک repo خودش است که به‌عنوان مستاجر Flux معرفی شده. انتشار v1.5.0 از orders-api چنین پیش می‌رود:

text
1  orders-api repo: tag v1.5.0 -> CI builds, tests, scans, signs ghcr.io/acme/orders-api:1.5.0@D
2  Image Updater commits 1.5.0 to apps/orders-api/overlays/staging (git write-back)
3  Argo CD staging: sync, PostSync smoke, Healthy; notification to #orders
4  promote-to-prod workflow opens PR (tag + digest D); orders team approves; merge
5  ApplicationSet-generated orders-api-prod syncs in the sync window; Rollouts canary 10% -> 100%
6  metrics: argocd_app_info{name="orders-api-prod", health_status="Healthy"}

قرارداد میان سرویس‌ها، شامل API و رویداد، هنوز نسخه‌داری می‌خواهد؛ GitOps فقط تضمین می‌کند آنچه اجرا می‌شود همان چیزی باشد که بازبینی شده است.

دادهٔ توزیع‌شده (Distributed data): چند Cluster، منطقه و Registry ​

در مقیاس مجموعهٔ بزرگ Clusterها، خود مرجع حقیقت به وابستگی تبدیل می‌شود. اگر GitHub قطع شود تغییری اعمال نمی‌شود؛ اگر هر Cluster هر دو دقیقه Poll کند، میزبان Git شما را محدود می‌کند. الگوها: Webhook همراه Poll دیرتر؛ OCI artifact تکثیرشده به مخزن تصویر (Registry) منطقه‌ای، تا هر Cluster پیکربندی امضاشده را از نزدیک بگیرد و Digest و هویت cosign را بررسی کند؛ برچسب Cluster برای هدایت Cluster generator در ApplicationSet تا منطقهٔ تازه برنامهٔ درست را بگیرد؛ تقسیم Controller به Shard برای Hub بزرگ Argo CD؛ یا Agent برای هر Cluster با Flux یا Argo CD تا قطعی Hub، Reconciliation را متوقف نکند. داده بیرون Git می‌ماند؛ پایگاه داده تکثیر خودش را دارد. GitOps اشیای Operator را مدیریت می‌کند، نه ردیف‌ها را.

مسیر افزایش مقیاس (Scaling path): یک، ده و صد برابر ​

مقیاسRepository و چیدمانAgentهاتحویل
1x؛ یک تیم و یک ClusterConfig repo به‌شکل Monorepo و Overlay هر محیطیک Argo CD یا FluxImage automation به Staging، PR به Prod
10x؛ چند تیم و 2-5 Clusterrepo هر تیم یا CODEOWNERS؛ ApplicationSet و مستاجرArgo CD HA با Project یا Flux هر Cluster با Multi-tenancyWebhook، Sync window، اعلان و هشدار OutOfSync
100x؛ مجموعهٔ بزرگ و مناطق متعددclusters/<name> ساخته‌شده از برچسب Cluster؛ OCI artifactsArgo CD تقسیم‌شده یا Flux هر Cluster؛ Kargo برای PromotionArtifact امضاشده، Registry منطقه‌ای و تحویل تدریجی در همه‌جا

آزمایشگاه (Lab) ​

برچسب اجرا: طبق قاعدهٔ هزینهٔ AUTHORING، ایجاد Kubernetes Cluster در محیط ساخت این فصل مجاز نیست. مراحل یک تا چهار روی میزبان اجرا شده‌اند؛ macOS، Go 1.27.4 و kubectl client v1.36.1 همراه Kustomize v5.8.1. خروجی واقعی در pipeline/sources/gitops-argocd-flux/lab-host-output.txt ذخیره شده است. مراحل پنج تا هشت مورد انتظارند و اجرا نشده‌اند؛ خروجی آن‌ها فقط شکل کلی یا جای‌نگهدار است، نه مقدار ساختگی.

۱. رندر تمام Overlayها مانند Agentها؛ اجراشده روی میزبان ​

bash
cd docs/snippets/platform/gitops-argocd-flux
scripts/render-overlays.sh ~/.docker/bin/kubectl
# ok   apps/orders-api/overlays/preview         1 Deployment, 1 Service
#      images: ghcr.io/acme/orders-api:1.4.2
# ok   apps/orders-api/overlays/prod            1 Deployment, 1 Service
#      images: ghcr.io/acme/orders-api:1.4.2@sha256:0b7e2a3c5d9f41e6a8b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3
# ok   apps/orders-api/overlays/staging         1 Deployment, 1 Service
#      images: ghcr.io/acme/orders-api:1.5.0
# ok   apps/shop-laravel/overlays/prod          2 Deployment, 2 Job, 1 Service
#      images: ghcr.io/acme/shop-app:2.7.0 ghcr.io/acme/shop-web:2.7.0
# ok   apps/shop-laravel/overlays/staging       2 Deployment, 2 Job, 1 Service
#      images: ghcr.io/acme/shop-app:2.8.1 ghcr.io/acme/shop-web:2.8.1
# ok   infrastructure/namespaces                2 Namespace
#      images: none

به Image مربوط به Prod دقت کنید: با وجود هم‌زمان newTag و digest، Kustomize مقدار name:tag@digest می‌نویسد. Digest تعیین می‌کند چه چیزی دریافت شود.

خروجی رندر Application پیش‌نمایش برای PR شمارهٔ ۴۲ همان Kustomization پوشاننده با namespace: و Image مربوط به PR است؛ یعنی کاری که kustomize.namespace و kustomize.images در ApplicationSet پیش‌نمایش انجام می‌دهند. این بخش روی میزبان اجرا شده است:

bash
cat sim/kustomization.yaml
# namespace: orders-api-pr-42
# resources: [../config-repo/apps/orders-api/overlays/preview]
# images: [{name: ghcr.io/acme/orders-api, newTag: pr-4f2a9c1e}]
kubectl kustomize sim | grep 'namespace:\|image:'
#   namespace: orders-api-pr-42
#   namespace: orders-api-pr-42
#       - image: ghcr.io/acme/orders-api:pr-4f2a9c1e
bash
#!/usr/bin/env bash
# Render every overlay of the config repository exactly as Argo CD's repo-server and
# Flux's kustomize-controller would (kustomize build), without a cluster.
# Usage: scripts/render-overlays.sh [kubectl]   (default: kubectl on PATH)
set -euo pipefail
kubectl=${1:-kubectl}
cd "$(dirname "$0")/../config-repo"
status=0
for dir in apps/*/overlays/* infrastructure/*; do
  if out=$("$kubectl" kustomize "$dir" 2>&1); then
    kinds=$(printf '%s\n' "$out" | awk '/^kind:/{print $2}' | sort | uniq -c | awk '{printf "%s %s, ", $1, $2}')
    images=$(printf '%s\n' "$out" | awk '/image:/{print $NF}' | sort -u | tr '\n' ' ')
    printf 'ok   %-40s %s\n     images: %s\n' "$dir" "${kinds%, }" "${images:-none}"
  else
    printf 'FAIL %s\n%s\n' "$dir" "$out"; status=1
  fi
done
exit $status

۲. تست سیاست Repository؛ اجراشده روی میزبان ​

bash
cd go && gofmt -l . && go vet ./... && go test -race -count=1 ./...
# ?   	academy/gitops-argocd-flux/cmd/driftdiff	[no test files]
# ?   	academy/gitops-argocd-flux/cmd/imagebump	[no test files]
# ok  	academy/gitops-argocd-flux/drift	1.292s
# ok  	academy/gitops-argocd-flux/imagebump	1.287s
# ok  	academy/gitops-argocd-flux/repocheck	1.419s

برای دیدن عملکرد Gate، یک قاعده را بشکنید: در clusters/staging/image-automation.yaml مقدار push.branch: image-updates/shop-prod را به main تغییر دهید و دوباره اجرا کنید. این آزمایش روی میزبان انجام و سپس تغییر برگردانده شده است:

text
--- FAIL: TestImageAutomationRules
    repocheck_test.go:170: apps/shop-laravel/overlays/prod/kustomization.yaml: prod marker updated by an automation that pushes straight to main

۳. Drift: آنچه Agent گزارش می‌کرد؛ اجراشده روی میزبان ​

فایل desired خروجی واقعی kubectl kustomize برای Overlay مربوط به Prod است؛ live مثالی دست‌نویس از پاسخ Cluster پس از یک هفته است: پیش‌فرض‌ها، Status، تعداد هفت Replica از HPA، یک Hotfix با kubectl set image و ConfigMap که قبلاً متعلق به برنامه بوده است.

bash
# still in the go/ directory from step 2
go run ./cmd/driftdiff -desired drift/testdata/desired-orders-api-prod.yaml \
  -live drift/testdata/live-orders-api-prod.yaml -app orders-api-prod -ignore /spec/replicas; echo "exit=$?"
# RequiresPruning  /ConfigMap:shop-prod/orders-api-flags
# Synced           /Service:shop-prod/orders-api
# OutOfSync        apps/Deployment:shop-prod/orders-api
#     /spec/template/spec/containers/orders-api/image: desired ghcr.io/acme/orders-api:1.4.2@sha256:0b7e...e2f3, live ghcr.io/acme/orders-api:1.4.3-hotfix
# application: OutOfSync
# exit status 1
# exit=1

Digest اینجا کوتاه شده؛ خروجی ذخیره‌شده مقدار کامل را دارد. Service با وجود دوازده فیلد اضافی در شیء زنده Synced است. هفت Replica حتی بدون -ignore گزارش نمی‌شود، چون Base فیلد replicas ندارد؛ بدون Flag هم همان خروجی را می‌گیرید. kube-root-ca.crt گزارش نمی‌شود چون هیچ‌چیز آن را رهگیری نمی‌کند. RequiresPruning برچسب این مدل است؛ Argo CD برنامه را OutOfSync و منبع را نیازمند Prune نشان می‌دهد.

۴. ویرایش برای Promotion؛ اجراشده روی میزبان روی کپی موقت ​

bash
# still in go/; work on a temporary copy, never on the overlay itself
T=$(mktemp); cp ../config-repo/apps/orders-api/overlays/prod/kustomization.yaml "$T"
go run ./cmd/imagebump -file "$T" -image ghcr.io/acme/orders-api \
  -tag 1.5.0 -digest sha256:1111111111111111111111111111111111111111111111111111111111111111
# $T: ghcr.io/acme/orders-api -> 1.5.0 sha256:1111111111111111111111111111111111111111111111111111111111111111
diff ../config-repo/apps/orders-api/overlays/prod/kustomization.yaml "$T"; rm "$T"
# 13c13
# <     newTag: "1.4.2"
# ---
# >     newTag: "1.5.0"
# 15c15
# <     digest: sha256:0b7e2a3c5d9f41e6a8b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3
# ---
# >     digest: sha256:1111111111111111111111111111111111111111111111111111111111111111

۵. Argo CD: نصب، ثبت و Sync؛ مورد انتظار، اجرا نشده ​

bash
kubectl create namespace argocd
kubectl apply -n argocd --server-side --force-conflicts -f https://raw.githubusercontent.com/argoproj/argo-cd/v3.6.3/manifests/install.yaml
# the root app belongs to the "platform" project, which lives inside the directory the
# root app syncs: create that one project by hand first, then the root app adopts it
kubectl apply -f config-repo/argocd/project-platform.yaml
kubectl apply -f config-repo/argocd/root-app.yaml        # app of apps: projects, ApplicationSets, cluster Secret
argocd app list
# NAME                        CLUSTER     NAMESPACE     PROJECT  STATUS     HEALTH       ...
# argocd/root                 in-cluster  argocd        platform Synced     Healthy
# argocd/orders-api-staging   in-cluster  shop-staging  shop     Synced     Healthy
# ... (one row per generated Application)
argocd app diff orders-api-prod          # exit code non-zero when there is a diff
argocd app history orders-api-prod

۶. Drift و Self-heal روی برنامهٔ زنده؛ مورد انتظار، اجرا نشده ​

bash
kubectl -n shop-staging set image deploy/orders-api orders-api=ghcr.io/acme/orders-api:9.9.9
argocd app get orders-api-staging       # Sync Status: OutOfSync, then Synced again a few seconds later (selfHeal)
kubectl -n shop-staging get deploy orders-api -o jsonpath='{.spec.template.spec.containers[0].image}'
# ghcr.io/acme/orders-api:1.5.0

۷. Flux: Bootstrap با Image automation و مشاهدهٔ ورود Tag؛ مورد انتظار، اجرا نشده ​

bash
flux bootstrap github --components-extra=image-reflector-controller,image-automation-controller \
  --owner=acme --repository=shop-config --branch=main --path=clusters/staging --read-write-key
flux get kustomizations
# NAME                   REVISION            SUSPENDED  READY  MESSAGE
# flux-system            main@sha1:<sha>     False      True   Applied revision: main@sha1:<sha>
# infrastructure         main@sha1:<sha>     False      True   Applied revision: main@sha1:<sha>
# shop-laravel-staging   main@sha1:<sha>     False      True   Applied revision: main@sha1:<sha>
kubectl -n flux-system get imagepolicy shop-app   # status shows the latest image ghcr.io/acme/shop-app:<newest 2.x tag>
git pull && git log -1 --stat           # commit by fluxcdbot touching overlays/staging/kustomization.yaml
flux events --for Kustomization/shop-laravel-staging

۸. Rollback با Revert در برابر دکمه؛ مورد انتظار، اجرا نشده ​

bash
git revert --no-edit <promotion-sha> && git push    # PR in real life
argocd app wait orders-api-prod --sync --health
argocd app rollback orders-api-prod                 # refused while automated sync is enabled

بدفهمی‌های رایج (Common misconceptions) ​

باورواقعیت
GitOps یعنی YAML در Gitدریافت خودکار و Reconciliation پیوسته هم لازم است
Git اجباری استهر State store با نسخهٔ تغییرناپذیر؛ OCI artifacts هم کار می‌کنند، با نام "Gitless"
Argo CD پیش‌فرض تغییر دستی را برمی‌گرداندفقط با selfHeal: true؛ Automated sync هم نیازمند فعال‌سازی است
Automated sync منابع حذف‌شده را پاک می‌کندفقط با prune: true
Synced یعنی انتشار کار می‌کندHealth مستقل است؛ Synced همراه Degraded رایج است
argocd app rollback بازگشت GitOps استبا Auto-sync روشن رد می‌شود و Git را ناهماهنگ باقی می‌گذارد؛ Commit را Revert کنید
شاخهٔ هر محیط تمیز استتفاوت پنهان و Drift ناشی از Merge؛ از پوشه روی main استفاده کنید
Image automation، Cluster را به‌روز می‌کنددر Git می‌نویسد؛ Agent، Commit را مستقر می‌کند
Argo CD Image Updater پیش‌فرض در Git ثبت می‌کندWrite-back پیش‌فرض argocd است؛ داخل Cluster و "pseudo-persistent"
Flux، Image automation نصب می‌کند--components-extra لازم دارد
repo خصوصی نگهداری Secret ساده را مجاز می‌کندمستندات Flux آن را "regardless of the visibility" ناامن می‌دانند
ApplicationSet برای هر تیم امن استفقط مدیر؛ می‌تواند در هر Project برنامه بسازد و Secretهای Argo CD را بخواند
Webhook اجباری استPolling کار می‌کند؛ Webhook فقط تأخیر را کم می‌کند
رفتار Helm در Argo CD و Flux یکسان استArgo CD رندر و Apply می‌کند؛ Flux انتشار واقعی Helm اجرا می‌کند

چکیده (Cheat sheet) ​

موضوعبه خاطر بسپارید
اصول (Principles)اعلانی، نسخه‌دار و تغییرناپذیر، دریافت خودکار و Reconciliation پیوسته
Push و PullCI در Git می‌نویسد؛ Agent داخل Cluster، Apply می‌کند؛ اعتبارنامهٔ Cluster در CI نیست
چیدمان (Layout)Config repo، فقط main، Overlay هر محیط، CODEOWNERS روی Prod
اجزای Argo CDapi-server برای UI/CLI/RBAC/Webhook؛ repo-server برای رندر؛ application-controller برای Diff/Sync؛ Redis برای Cache
سیاست Syncautomated + prune + selfHeal؛ retry؛ ServerSideApply=true
ترتیب (Ordering)Argo CD: PreSync سپس Waveها سپس PostSync؛ Flux: dependsOn و wait
وضعیت (Status)Sync با Synced/OutOfSync از Health با Healthy/Progressing/Degraded جداست
نادیده‌گرفتن (Ignore)ignoreDifferences / driftDetection.ignore؛ بهتر: حذف فیلد متعلق به Controller
ApplicationSetMatrix حاصل Git × Cluster؛ PR generator برای Preview؛ فقط مدیر
اشیای FluxGitRepository/OCIRepository سپس Kustomization/HelmRelease؛ Provider/Alert/Receiver
Image automationImageRepository سپس ImagePolicy، ImageUpdateAutomation، نشانگر و Commit
ارتقا (Promotion)PR با Tag و Digest در overlays/prod؛ Kargo برای چند Stage
بازگشت (Rollback)git revert؛ argocd app rollback به Auto-sync خاموش نیاز دارد
اسرار (Secrets)SOPS، Sealed Secrets یا ESO؛ هرگز متن ساده
سنجه‌ها (Metrics)argocd_app_info{sync_status,health_status}؛ gotk_reconcile_duration_seconds؛ هشدار برای OutOfSync بیش از 15m
ضدالگوها (Anti-patterns)kubectl apply از CI، cluster-admin در CI، latest، Project پیش‌فرض و شاخهٔ هر محیط

خودآزمایی: پرسش و پاسخ (Self-check: questions & answers) ​

نمایش:
  • حیاتی تقریباً در هر مصاحبه پرسیده می‌شود
  • مهم پرتکرار؛ در سطح senior انتظار می‌رود
  • تکمیلی عمق بیشتر؛ تمایز ایجاد می‌کند

۱ — چهار اصل OpenGitOps چیست و کار CI که در هر Push، kubectl apply -k اجرا می‌کند کدام دو اصل را نقض می‌کند؟ حیاتی ​

پاسخ

پاسخ: اعلانی‌بودن؛ نسخه‌داری و تغییرناپذیری؛ دریافت خودکار؛ آشتی‌دهی پیوسته. کار CI می‌تواند با Manifest در Git دو اصل نخست را رعایت کند، اما به‌جای Pull عامل، Push می‌کند و به‌جای مشاهده و اصلاح پیوستهٔ Drift فقط در هر اجرا Apply می‌کند. بنابراین تغییر دستی و Manifest حذف‌شده دیده نمی‌شوند. اصول را ببینید.

۲ — Application شما در Argo CD دارای automated: {} است. کسی Manifest یک Deployment را از Git حذف و دیگری Deployment دیگری را دستی Scale می‌کند. چه رخ می‌دهد و چه چیزی را تغییر می‌دهید؟ حیاتی ​

پاسخ

پاسخ: هیچ‌کدام اصلاح نمی‌شود؛ Automated sync پیش‌فرض Prune ندارد و تغییر زنده بدون Self-heal، Sync را فعال نمی‌کند؛ برنامه OutOfSync می‌شود. prune: true و selfHeal: true بگذارید. اشیای حساس را با Prune=false یا Prune=confirm محافظت کنید. سیاست Sync.

۳ — چرا شاخهٔ جدا برای هر محیط ضدالگو است و جایگزینش چیست؟ حیاتی ​

پاسخ

پاسخ: تفاوت محیط‌ها در تاریخچهٔ Merge پنهان می‌شود؛ Merge تغییر نامرتبط را به Prod می‌برد؛ Cherry-pickها از هم دور می‌شوند و مقایسهٔ محیط‌ها با یک فرمان ممکن نیست. یک شاخهٔ main با پوشهٔ هر محیط، شامل Kustomize overlays یا Helm values هر محیط، داشته باشید. Promotion یک Diff کوچک و بازبینی‌شده در overlays/prod می‌شود. چیدمان Repository.

۴ — برنامه Synced ولی Degraded است. هر واژه چه می‌گوید و کجا را بررسی می‌کنید؟ حیاتی ​

پاسخ

پاسخ: Synced یعنی اشیای زنده با رندر Git برابرند. Degraded یعنی Workload کار نمی‌کند؛ مثلاً Pod در CrashLoopBackOff است یا Rollout شکست خورده. Rollout مربوط به Deployment، رویداد Pod و لاگ‌ها را بررسی کنید، نه Git را. با Revert یا Commit تازه اصلاح کنید. سلامت.

۵ — Migrationهای Laravel را چگونه در Argo CD یک‌بار در هر انتشار اجرا می‌کنید و چرا همچنان باید با گذشته سازگار باشند؟ حیاتی ​

پاسخ

پاسخ: Job با Annotationِ argocd.argoproj.io/hook: PreSync و BeforeHookCreation، فرمان php artisan migrate --force --isolated را اجرا می‌کند. شکست آن Sync را پیش از Apply شدن Podهای تازه متوقف می‌کند. Podهای قدیمی حین به‌روزرسانی تدریجی (Rolling update) و پس از Rollback با Revert همچنان خدمت می‌دهند؛ Schema باید برای هر دو نسخه کار کند. ابتدا Expand و بعد Contract. Wave و Hook.

۶ — چرا Rollback در GitOps یعنی git revert و چه زمانی argocd app rollback شکست می‌خورد؟ حیاتی ​

پاسخ

پاسخ: Revert، Commit تازه‌ای می‌سازد که وضعیت مطلوب قبلی را برمی‌گرداند؛ Git و Cluster هماهنگ و سابقهٔ ممیزی کامل می‌مانند. argocd app rollback ورودی قدیمی تاریخچه را Sync می‌کند و "cannot be performed against an application with automated sync enabled". پس از آن Git هنوز نسخهٔ خراب را نام می‌برد. Rollback.

۷ — جریان Image automation برچسب Laravel در Flux را از Push به Registry تا Pod در حال اجرا شرح دهید. مهم ​

پاسخ

پاسخ: image-reflector-controller، ImageRepository را اسکن می‌کند؛ ImagePolicy با filterTags برچسب‌ها را فیلتر و جدیدترین را در بازهٔ semver انتخاب می‌کند. image-automation-controller شاخه را Checkout می‌کند، فیلدهای دارای نشانگر {"$imagepolicy": "flux-system:shop-laravel:tag"} زیر update.path را بازنویسی می‌کند؛ یک سیاست برای هر دو Image برنامهٔ Laravel. سپس Commit و Push می‌کند؛ source-controller، Revision تازه را می‌گیرد و Kustomization اعمال می‌کند. برای Prod، push.branch با شاخهٔ Checkout فرق دارد تا تغییر به‌شکل PR برسد. Image automation.

۸ — چرا ApplicationSet و Repositoryهای app of apps فقط در اختیار مدیرند؟ مهم ​

پاسخ

پاسخ: می‌توانند در هر AppProject، Application بسازند؛ حتی Project مجاز به استقرار در Namespace خود Argo CD که دسترسی مدیریتی می‌دهد. می‌توانند سریع تعداد زیادی Application بسازند یا حذف کنند؛ Git generator هم می‌تواند Secretهای Namespaceِ Argo CD را به‌شکل Header احراز هویت به URL بفرستد. project قالب را ثابت بگذارید و افراد مجاز به Push در مسیر منبع را محدود کنید. ApplicationSet.

۹ — HPA، Deployment را Scale می‌کند و Argo CD هر چند دقیقه OutOfSync نشان می‌دهد. دو راه‌حل و انتخاب ترجیحی شما چیست؟ مهم ​

پاسخ

پاسخ: replicas را از Manifest در Git حذف کنید؛ این انتخاب بهتر است چون HPA مالک فیلد می‌شود و چیزی برای Ignore باقی نمی‌ماند. یا برای Deployment، ignoreDifferences با jsonPointers: [/spec/replicas] بگذارید؛ اگر Sync هم نباید مقدار را برگرداند، RespectIgnoreDifferences=true لازم است. در HelmReleaseهای Flux از driftDetection.ignore استفاده کنید. Diffing.

۱۰ — روش استقرار Chart در Argo CD و Flux چه تفاوتی دارد؟ مهم ​

پاسخ

پاسخ: repo-server در Argo CD، helm template اجرا می‌کند و Argo CD خروجی را Apply می‌کند؛ پس Helm release وجود ندارد، helm list خالی است و Helm hookها به Hookهای Argo CD نگاشت می‌شوند. helm-controller در Flux نصب و Upgrade واقعی Helm انجام می‌دهد، تاریخچهٔ انتشار را نگه می‌دارد، Helm test اجرا می‌کند و شکست را با Retry، Rollback پیش‌فرض یا Uninstall اصلاح می‌کند. با driftDetection.mode: enabled، Drift را هم اصلاح می‌کند. HelmRelease.

۱۱ — هنگام رخداد باید Deployment زنده را دستی تغییر دهید. زیر GitOps چگونه ایمن عمل می‌کنید؟ مهم ​

پاسخ

پاسخ: ابتدا Reconciliation همان برنامه را Suspend کنید؛ در Flux با flux suspend kustomization <name> یا Annotationِ kustomize.toolkit.fluxcd.io/reconcile: disabled روی یک شیء. در Argo CD، Automated sync همان Application را خاموش کنید؛ اگر ApplicationSet آن را ساخته، باید ignoreApplicationDifferences برای /spec/syncPolicy داشته باشد، وگرنه ویرایش سیاست Sync شیء تولیدشده "will, however, have no effect". تغییر را انجام دهید، اصلاح واقعی را با PR ثبت و سپس Resume کنید. وگرنه Self-heal یا بازهٔ بعدی، تغییر شما را وسط رخداد برمی‌گرداند. Drift و Self-heal.

۱۲ — Kargo به بیان مستندات خودش چه چیزی به Argo CD اضافه می‌کند؟ تکمیلی ​

پاسخ

پاسخ: Promotion: "Promotions are different from deployments" و استقرار "is left to a GitOps agent like Argo CD". Warehouseهای Kargo، Repositoryها را می‌پایند و Revision تازه را در Freight بسته‌بندی می‌کنند؛ همان "a 'meta-artifact'". Freight با Promotion میان Stageهای مرتبط جابه‌جا می‌شود. Promotion.

۱۳ — چرا پیکربندی را به‌جای Git clone به‌شکل OCI artifact امضاشده به Clusterهای Production می‌رسانید؟ تکمیلی ​

پاسخ

پاسخ: میزبان Git دیگر وابستگی Production نیست و Registry منطقه‌ای می‌تواند Artifact را نزدیک هر Cluster ارائه کند. Artifact با محتوا آدرس‌دهی می‌شود و OCIRepository پیش از Apply، امضای cosign را بررسی می‌کند؛ مثلاً امضای Keyless متکی به هویت Workflowِ CI در Config repo. Git همچنان رابط انسان می‌ماند. منابع Flux.

واژه‌نامه (Glossary) ​

اصطلاحمعنی
GitOpsادارهٔ سیستم از وضعیت مطلوب نسخه‌دار که Agent دریافت و پیوسته آشتی‌دهی می‌کند
اصول OpenGitOps (OpenGitOps principles)چهار اصل گروه کاری GitOps در CNCF؛ v1.0.0 در 2021
اعلانی (Declarative)توصیف نتیجهٔ نهایی، نه مراحل رسیدن به آن
نسخه‌دار و تغییرناپذیر (Versioned and immutable)نگهداری همهٔ نسخه‌های وضعیت مطلوب بدون بازنویسی
دریافت خودکار (Pulled automatically)Agent خودش وضعیت مطلوب را دریافت می‌کند
آشتی‌دهی پیوسته (Continuously reconciled)مقایسه و اصلاح ادامه دارد و یک‌باره نیست
وضعیت مطلوب (Desired state)پیکربندی کافی برای بازسازی سیستم، نه دادهٔ آن
محل نگهداری وضعیت (State store)نگهداری تغییرناپذیر وضعیت مطلوب با کنترل دسترسی؛ Git یا مخزن تصویر (Registry) در OCI
حلقهٔ آشتی‌دهی (Reconciliation loop)دریافت، رندر، Diff، Apply، بررسی Health و تکرار
انحراف (Drift)دورشدن وضعیت زنده از وضعیت مطلوب
خود‌ترمیمی (Self-heal)Apply دوبارهٔ وضعیت مطلوب پس از Drift؛ selfHeal در Argo CD
تشخیص انحراف (Drift detection)مرحلهٔ Diff؛ driftDetection در Flux HelmRelease
استقرار فشاری و کششی (Push vs pull deployment)Apply از CI در برابر Pull عامل داخل Cluster
Repository پیکربندی (Config repository)repo حاوی پیکربندی قابل استقرار، جدا از کد
Repository برنامه (App repository)repo حاوی کد برنامه
Monorepoپیکربندی همهٔ محیط‌ها در یک repo و شاخه
پوشهٔ هر محیط (Per-environment directories)overlays/staging و overlays/prod روی یک شاخه
ضدالگوی شاخهٔ هر محیط (Branches per environment anti-pattern)شاخهٔ Git جدا برای هر محیط و Drift ناشی از Merge
پوشش‌های Kustomize (Kustomize overlays)Base و Patch هر محیط؛ فصل Helm/Kustomize
مقادیر Helm هر محیط (Helm values per env)فایل‌های values-<env>.yaml برای محیط‌ها
Argo CDابزار CD در GitOps از CNCF با UI، Project و RBAC
api-serverargocd-server: رابط gRPC/REST، UI، RBAC، SSO و Webhook
repo-serverمؤلفهٔ Argo CD برای Clone و رندر Manifest
application-controllerController مقایسه و Sync کردن Applicationها
RedisCache دورریختنی Argo CD
Application CRDشیء Argo CD شامل منبع، مقصد، Project و Sync policy
AppProjectمحافظ‌های Argo CD: repo، مقصد، Kind، نقش و پنجرهٔ زمانی
سیاست همگام‌سازی (Sync policy)spec.syncPolicy: automated، prune، selfHeal، retry و options
همگام‌سازی خودکار (Automated sync)Sync بدون کلیک هنگام OutOfSync
هرس (Prune)حذف منابعی که از منبع برداشته شده‌اند
گزینه‌های Sync (Sync options)Flagهای هر برنامه یا منبع؛ مانند ServerSideApply و PruneLast
موج‌های همگام‌سازی (Sync waves)Annotation با نام sync-wave برای ترتیب منابع
قلاب‌های همگام‌سازی (Sync hooks)منابع اجراشونده در PreSync، Sync، PostSync، SyncFail، PreDelete و PostDelete
وضعیت سلامت (Health status)Healthy، Progressing، Degraded، Suspended، Missing و Unknown
OutOfSyncوضعیت زنده با هدف رندرشده متفاوت است
ignoreDifferencesقواعد Argo CD برای کنارگذاشتن فیلد از Diff
ApplicationSetقالب همراه Generator برای ساخت Application
مولد Git (Git generator)پارامتر از پوشه یا فایل repo
مولد Cluster (Cluster generator)پارامتر از Secretهای Cluster در Argo CD
مولد Matrix (Matrix generator)حاصل‌ضرب پارامترهای دو Generator
مولد Pull request (Pull request generator)پارامتر از PR باز برای Preview
App of appsApplication که Manifestهایش Application هستند
Argo CD RBACسیاست‌های Casbin در argocd-rbac-cm
ورود یکپارچه (SSO)ورود از طریق Dex یا ارائه‌دهندهٔ OIDC
Argo CD NotificationsTriggerها، قالب‌ها و سرویس‌ها در argocd-notifications-cm
Argo CD Image UpdaterController تغییر Tag تصویر برنامه‌های Argo CD با ImageUpdater CR
FluxToolkit کنترل‌گرهای GitOps در CNCF
source-controllerدریافت منابع Git/OCI/Helm/Bucket به‌شکل Artifact
kustomize-controllerساخت و Apply کردن Kustomization، Prune و رمزگشایی SOPS
helm-controllerاجرای Helm release برای اشیای HelmRelease
notification-controllerWebhook ورودی با Receiver؛ رویداد خروجی با Alert/Provider
image-reflector-controllerاسکن Registryها برای ImageRepository/ImagePolicy
image-automation-controllerنوشتن Tag انتخاب‌شده در Git
GitRepositoryمنبع Flux برای Git repo
OCIRepositoryمنبع Flux برای OCI artifact
مصنوع‌های OCI (OCI artifacts)Config یا Chart ذخیره‌شده در مخزن تصویر (Registry)
Kustomization در FluxCRD اعمال مسیر یک منبع؛ با فایل kustomization.yaml متفاوت است
HelmReleaseCRD در Flux برای Helm release
dependsOnترتیب میان Kustomizationها یا HelmReleaseها در Flux
بررسی سلامت (Health checks)healthChecks / wait در Flux روی اشیای Apply‌شده
ReceiverEndpoint وب‌هوک Flux برای فعال‌کردن Reconciliation
Alert، Providerمسیریابی و مقصد رویداد Flux
ImageRepositoryشیء Flux برای فهرست Tagهای Image
ImagePolicyقاعدهٔ Flux برای انتخاب جدیدترین Tag مجاز
ImageUpdateAutomationشیء Flux برای Commit برچسب‌های تازه در Git
نوشتن نتیجه در Git (Write back to Git)ثبت تغییر Image automation به‌جای Patch مستقیم Cluster
نشانگر $imagepolicyComment در YAML که به Flux می‌گوید کدام فیلد تغییر کند
flux bootstrapنصب Flux و Commit کردن Manifestهایش تا خودش را مدیریت کند
چندمستاجری (Multi-tenancy)Reconciliation مستاجرها با ServiceAccount اختصاصی آن‌ها
اسرار در GitOps (Secrets in GitOps)Secret رمز‌شده با SOPS/Sealed Secrets یا ارجاعی با ESO
ارتقای محیط (Environment promotion)بردن نسخهٔ آزموده‌شده به وضعیت مطلوب محیط بعد
PR تغییر Image tag (Image tag bump PR)PR تغییر یک Tag تصویر و Digest آن
KargoPlatform ارتقا با Warehouse، Freight، Stage و Promotion
بازگشت با Revert (Rollback by revert)git revert تغییر و سپس Sync توسط Agent
argocd app rollbackSync دوبارهٔ ورودی قدیمی تاریخچهٔ Application
Argo RolloutsController تحویل تدریجی با Canary و Blue-green
FlaggerOperator تحویل تدریجی برای Mesh/Ingress
Crossplaneچارچوب Control plane برای مدیریت منابع ابر از طریق CRD
tf-controller یا Tofu ControllerController در Flux برای Reconciliation منابع Terraform/OpenTofu
سنجه‌های Sync (Sync metrics)argocd_app_info، argocd_app_sync_total و gotk_* در Prometheus
kubectl apply از CIضدالگوی استقرار Push
cluster-admin در CIنگهداری اعتبارنامهٔ مدیریت کل Cluster در CI
شاخه‌های بلندعمر (Long-lived branches)شاخهٔ محیط یا قابلیت که هفته‌ها نگه داشته می‌شود
پنجرهٔ همگام‌سازی (Sync window)زمان‌بندی AppProject برای اجازه یا منع Sync
Annotation رهگیری (Tracking annotation)argocd.argoproj.io/tracking-id؛ روش تشخیص مالکیت در Argo CD

منابع (References) ​

ساخته‌شده توسط Morteza Negahi