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 و Pull | Push و 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 و AppProject | Application و 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 apps | ApplicationSet و app of apps |
| دسترسی و اعلان در Argo CD با RBAC، SSO و Notifications | RBAC، SSO و اعلانها |
| بهروزرسانی تصویر با Argo CD Image Updater | Image Updater |
| وظایف source-controller، kustomize-controller، helm-controller، notification-controller و کنترلگرهای تصویر | کنترلگرهای Flux |
| دریافت GitRepository، OCIRepository و OCI artifacts | منابع Flux |
Kustomization، dependsOn و Health checks | Kustomization در Flux |
| انتشار Helm با HelmRelease | HelmRelease |
| ورود و خروج رویداد با Receiver، Alert و Provider | اعلانهای Flux |
| ImageRepository، ImagePolicy و ImageUpdateAutomation و نوشتن نتیجه در Git | Image automation |
آمادهسازی با flux bootstrap و Multi-tenancy | Bootstrap و Multi-tenancy |
| تشخیص Drift، Self-heal و برگرداندن تغییر دستی | Drift و Self-heal |
| مدیریت Secrets با SOPS، Sealed Secrets و ESO | Secrets |
| Promotion محیط، PR تغییر Image tag و Kargo | Promotion |
مقایسهٔ Revert با argocd app rollback | Rollback |
| نقش Argo Rollouts و Flagger | تحویل تدریجی |
| آشنایی با Crossplane و tf-controller | GitOps برای زیرساخت |
| سنجههای 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 CD | Flux |
|---|---|---|
| واحد تحویل (Unit of delivery) | Application شامل منبع، مقصد و Sync policy | Kustomization یا HelmRelease که به شیء منبع اشاره دارد |
| گروهبندی و محافظها (Guardrails) | AppProject: repoهای منبع، مقصدها، Kindهای مجاز و نقشها | فضاهای نام (Namespaces) در Kubernetes و RBAC؛ عملکردن با هویت serviceAccountName |
| گسترش به چند مقصد (Fan-out) | مولدهای ApplicationSet؛ app of apps | Kustomizationهایی که Kustomization میسازند؛ یکی برای هر پوشهٔ Cluster |
| سرکشی پیشفرض (Poll) | 120 s بهعلاوهٔ حداکثر 60 s نوسان زمانی (Jitter) (timeout.reconciliation) | .spec.interval هر شیء؛ مستندات مفاهیم دربارهٔ Kustomization میگویند "every five minutes by default"؛ مقدار را شما تعیین میکنید |
| اصلاح Drift | selfHeal: true؛ پیشفرض خاموش | برای Kustomization در هر بازه فعال؛ برای HelmRelease با driftDetection.mode |
| ترتیب اجرا | Sync waves و Hookها: PreSync، Sync، PostSync، SyncFail، PreDelete و PostDelete | dependsOn میان Kustomizationها/HelmReleaseها؛ wait / healthChecks |
| Helm | رندر با helm template؛ در helm list نیست | انتشار واقعی Helm با helm-controller؛ در helm list هست |
| رابط کاربری (UI) و کاربران | Web UI، SSO با Dex یا OIDC، RBAC با Casbin | UI داخلی ندارد؛ Kubernetes RBAC و CLI با flux |
| خودکارسازی تصویر (Image automation) | Argo CD Image Updater، پروژهٔ جدا با ImageUpdater CR | image-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 |
وضعیتهایی که هر روز میبینید.
| وضعیت | ابزار | معنی | اولین بررسی |
|---|---|---|---|
| Synced | Argo CD | وضعیت زنده با رندر Git یکسان است | کاری لازم نیست؛ Health را هم ببینید |
| OutOfSync | Argo CD | حداقل یک شیء متفاوت است یا وجود ندارد | argocd app diff؛ مورد انتظار، اجرا نشده |
| Healthy / Suspended / Progressing / Missing / Degraded / Unknown | Argo CD | سلامت بار کاری (Workload) مستقل از Sync؛ بدترین فرزند وضعیت برنامه را تعیین میکند؛ ترتیب از سالمترین به ناسالمترین است | Rollout، Probeها و رویدادها |
| Ready=True | Flux | آخرین Reconciliation اعمال شده و با wait سلامت هم بررسی شده | flux get kustomizations |
Ready=False با دلیل BuildFailed، HealthCheckFailed، DependencyNotReady | Flux | خطای ساخت، Workload ناسالم یا آمادهنبودن dependsOn | flux events، flux tree |
| OutOfSync همراه منبع علامتخورده برای Prune | Argo CD | منبع متعلق به برنامه بوده، از Git حذف شده و Prune خاموش است: "The app will be out of sync if Argo CD expects a resource to be pruned" | Prune را فعال کنید یا یک Sync با انتخاب Prune انجام دهید |
چرا وجود دارد (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 جدا | ممیزی تمیز، دسترسی جدا، حذف حلقهٔ CI | repo دوم و مرحلهٔ Promotion |
| یک شاخه برای هر محیط | پوشهٔ هر محیط روی main | تفاوت محیطها روشن است؛ Drift ناشی از Merge ندارید | نظم در Overlayها |
| Tag تغییرپذیر | Tag همراه چکیدهٔ محتوا (Digest) در Git | Commit بایتهای دقیق را مشخص میکند؛ Rollback دقیق است | ابزار نوشتن Digest |
| تغییر دستی Tag | Image automation یا ربات Promotion | Staging سریع؛ 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)
| زمان | رویداد | منبع |
|---|---|---|
| 2016 | Flux: "was initially developed by Weaveworks and made open source in 2016" | بخش History در README مربوط به Flux v1 |
| 2017 | Argo: "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" دربارهٔ Flux | README مربوط به Flux v1 |
| آوریل 2020 | Argo: "accepted into the CNCF Incubator in April 2020" | اعلام CNCF |
| 8 اکتبر 2021 | OpenGitOps 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 v2 | Flux 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 |
| نوامبر 2026 | Argo 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."
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 CD | Application 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".
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؛ استقرار با CI | Pull؛ آشتیدهی با 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".
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 CD | Poll، 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 است.
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 اجرا میشوند.
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-server | Deployment | Replicaها؛ بدون وضعیت |
argocd-repo-server | Deployment | Replicaها؛ رندر به CPU محدود است |
argocd-application-controller | StatefulSet | Shardها؛ تقسیم Clusterها میان Replicaها |
argocd-redis | Deployment؛ در Manifestهای HA از Redis HA | Cache دورریختنی |
argocd-dex-server | Deployment | فقط هنگام استفاده از Dex |
| کنترلگرهای ApplicationSet و Notifications | Deploymentها | معمولاً یکی از هرکدام |
راهحل: برای 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 تعریف میشود.
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 دلخواه نمیگیرد |
destinations | shop-staging، shop-prod | هرگز argocd؛ دسترسی مدیریتی میدهد |
clusterResourceWhitelist | [] | Namespace و CRD از لایهٔ Platform میآیند |
namespaceResourceWhitelist | Deployment، ReplicaSet، Pod، Service، ConfigMap، Job، HPA، PDB | درخت UI را هم محدود میکند |
roles | ci-sync-staging | Token با حوزهٔ محدود برای CI |
syncWindows | اجازهٔ Prod در روزهای کاری 06:00-18:00، manualSync: true | Agent پنجرهٔ تغییر را اعمال میکند |
راهحل: برای هر تیم یا دامنه (Domain) یک Project بسازید؛ فقط Project مربوط به Platform اجازهٔ ورود به argocd داشته باشد:
# 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# 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.
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.prune | false | همیشه در GitOps؛ اشیای خاص را با Prune=false/confirm محافظت کنید |
automated.selfHeal | false | Production بدون تغییر دستی؛ زمان خاموشکردن را ببینید |
automated.allowEmpty | false | بهندرت؛ پیشفرض جلوی حذف همهچیز با Commit بد را میگیرد |
retry.limit | Automated sync: تعداد 5 تلاش در 5/10/20/40/80 s | صریح بنویسید، مانند limit: 5 و maxDuration: 3m، تا رفتار در Git دیده شود؛ -1 نامحدود است |
ServerSideApply=true | Apply سمت Client | اشیای بزرگ و مالکیت مشترک فیلد |
ApplyOutOfSyncOnly=true | Apply همهٔ اشیا | برنامه با هزاران شیء |
CreateNamespace=true | نبود Namespace باعث شکست است | محیط موقت مثل Preview؛ نه وقتی Platform مالک Namespace است |
راهحل: Application کامل سرویس Go برای Prod در ادامه آمده است. ApplicationSet فروشگاه هم همین شیء را میسازد؛ بنابراین root app این فایل را مستثنا میکند. در Repository واقعی یکی از این دو روش را نگه دارید:
# 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".
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 CD | Flux |
|---|---|---|
| مراحل قبل و بعد | PreSync / PostSync / SyncFail | فاز ندارد؛ Kustomization جدا با dependsOn یا Helm hook داخل HelmRelease واقعی |
| ترتیب منابع عادی | Sync waves | dependsOn میان 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 میخوانند:
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-envapiVersion: 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" را میپذیرد.
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 ننویسید.
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 CD | Flux |
|---|---|---|
| نادیدهگرفتن یک فیلد | ignoreDifferences.jsonPointers | driftDetection.ignore.paths در HelmRelease |
| نادیدهگرفتن فیلد Controller دیگر | managedFieldsManagers | مالکیت فیلد در Server-side apply؛ آن فیلدها را ننویسید |
| دستنخوردن فیلد هنگام Sync هم | RespectIgnoreDifferences=true | kustomize.toolkit.fluxcd.io/ssa: IfNotPresent؛ فقط ایجاد |
| دستنخوردن فیلدهای یک شیء هنگام Sync | ignoreDifferences همراه 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 را جایگزین میداند.
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 ثابت |
| Cluster | Secretهای Cluster در Argo CD با برچسبها | افزودنیها برای هر Cluster عملیاتی |
| Git؛ پوشه یا فایل | چیدمان repo یا فایل JSON/YAML | Application برای هر پوشهٔ Overlay |
| Matrix | حاصلضرب دو فرزند | برنامهها × Clusterها |
| Merge | مولد پایه با بازنویسی از دیگران | تغییر پیشفرض برای هر Cluster |
| Pull Request | PRهای باز GitHub، GitLab، Gitea، Bitbucket و غیره | محیط Preview |
| SCM Provider | Repositoryهای سازمان | یک برنامه برای هر Repository |
راهحل: ApplicationSet فروشگاه، ApplicationSet پیشنمایشها و root app:
# 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# 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# 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: trueSelector در Cluster generator فقط Cluster دارای Secret را پیدا میکند. چون "the default local cluster does not have a Secret"، Cluster محلی را صریح و با برچسب env تعریف میکنیم:
# 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 است.
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-cm | url، oidc.config یا dex.config، admin.enabled، timeout.reconciliation، روش رهگیری و سفارشیسازی منابع |
argocd-rbac-cm | policy.default، policy.csv، scopes |
argocd-notifications-cm | سرویسها، قالبها، Triggerها و context |
argocd-secret / Secretهای برچسبدار | Client secretها و Tokenها با ارجاع $key |
راهحل:
# 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# 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]# 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.
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 Updater | Image automation در Flux |
|---|---|---|
| نصب | پروژه و Controller جدا | --components-extra=image-reflector-controller,image-automation-controller |
| پیکربندی | ImageUpdater CR | ImageRepository + ImagePolicy + ImageUpdateAutomation |
| مقصد Tag | پارامتر Application، .argocd-source-<app>.yaml، Kustomization یا Helm values | هر فیلد YAML با نشانگر $imagepolicy |
| جریان PR | gitConfig.branch: "base:target" روی شاخهٔ دیگر مینویسد | git.push.branch متفاوت از شاخهٔ Checkout |
راهحل:
# 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 است.
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 تصویر را اجرا نمیکند.
| Controller | CRDها | نصب پیشفرض |
|---|---|---|
| source-controller | GitRepository، OCIRepository، HelmRepository، HelmChart، Bucket | بله |
| kustomize-controller | Kustomization | بله |
| helm-controller | HelmRelease | بله |
| notification-controller | Provider، Alert، Receiver | بله |
| image-reflector-controller | ImageRepository، ImagePolicy | خیر؛ --components-extra |
| image-automation-controller | ImageUpdateAutomation | خیر؛ --components-extra |
| source-watcher | ArtifactGenerator | خیر؛ --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://....
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"دریافت میشود.
| منبع | کاربرد | بررسی اصالت |
|---|---|---|
| GitRepository | Config repo و repo مستاجرها | امضای Commit با PGP از طریق verify |
| OCIRepository | Config artifact و Chart در OCI | cosign با کلید یا Keyless؛ notation |
| HelmRepository | repo کلاسیک Helm روی HTTP | منشأ (Provenance) Chart در Workflow آن |
| Bucket | Storage سازگار با S3 | فقط کنترل دسترسی |
راهحل:
# 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."
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 برای سرعت |
retryInterval | 1m-2m | تلاش سریعتر پس از شکست |
prune | true | جمعآوری اشیای حذفشده |
wait | true برای shop-laravel | Ready یعنی Rollout و Jobها کامل شدهاند |
healthChecks | Deployment orders-api | فهرست صریح وقتی wait بیشازحد گسترده است |
dependsOn | infrastructure | Namespace پیش از برنامه |
decryption | sops / sops-age | Secret رمزشده در Git |
timeout | 5m-10m | سقف زمان Build، Apply و Health check |
راهحل: Kustomization برنامهٔ Laravel و سرویس Go:
# 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# 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# 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-ageHelmRelease: انتشار واقعی 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" است.
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 در Flux | Argo CD با منبع Helm |
|---|---|---|
نمایش در helm list | بله | خیر |
| Helm hooks | Hook واقعی Helm | نگاشت به Hookهای Argo CD |
| Upgrade ناموفق | Remediation: تلاش مجدد، Rollback، Uninstall | Sync ناموفق؛ سیاست Retry |
| Drift | driftDetection.mode با warn / enabled | selfHeal |
راهحل:
# 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 را اضافه میکند.
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 | ورودی؛ Webhook | type، events، secretRef، resources |
| Provider | خروجی؛ مقصد | type، address، channel، secretRef |
| Alert | خروجی؛ مسیریابی | providerRef، eventSources، eventSeverity، eventMetadata |
راهحل:
# 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 است.
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 | پاسخ به کدام پرسش |
|---|---|---|
| ImageRepository | image-reflector-controller | چه Tagهایی موجود است؟ |
| ImagePolicy | image-reflector-controller | جدیدترین Tag مجاز کدام است؟ |
| ImageUpdateAutomation | image-automation-controller | کدام فایل، کدام شاخه و چه پیام Commit؟ |
نشانگر $imagepolicy | داخل YAML شما | کدام فیلد چه مقداری بگیرد؟ |
راهحل: سیاستها و دو Automation در ادامهاند؛ نشانگرها داخل Overlay هستند:
# 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# 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 هستند.
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-key | Deploy key با حق نوشتن؛ لازم برای Image automation |
serviceAccountName | استفاده از هویت مشخص برای هر Kustomization/HelmRelease |
--no-cross-namespace-refs=true | مستاجر نمیتواند به منبع Namespace دیگر ارجاع دهد |
--default-service-account=default | شیء بدون serviceAccountName هویت محلی Namespace میگیرد |
راهحل:
# 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 انحراف را اصلاح میکند.
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 است.
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 CD | KMS یا کلید 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.
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 Updater | Image Updater | بازبینی PR |
| Kargo Promotion | Kargo با مراحل Git commit، PR و Argo CD update | اعتبارسنجی Stage، دستی یا خودکار |
| Commit مستقیم به main | هر دارندهٔ حق Push | ندارد؛ برای Prod پرهیز کنید |
راهحل: Workflow ارتقا و ابزارش در ادامهاند. هر فایلی که نسخهٔ Prod را مشخص میکند باید در همان PR تغییر کند؛ اگر فقط Overlay تغییر کند، HelmRelease در Flux که values.image خودش را دارد روی نسخهٔ قدیمی میماند:
# 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 هنوز نسخهٔ جدید را میخواهد.
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، آموزش داده شدهاند.
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 Rollouts | Argo CD؛ همخانوادهاند و سلامت Rollout در برنامه دیده میشود | Rollout، AnalysisTemplate |
| Flagger | Flux؛ اکوسیستم نگهدارندگان مشترک | 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 در زیرساخت بهشکل کد است.
# 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-system1 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 |
|---|---|---|
| Crossplane | CRDهای Kubernetes برای منابع ابر و Compositionها | پیوسته با Controllerهای Provider |
| Tofu Controller یا tf-controller | اجرای Terraform/OpenTofu با Flux | در هر بازه؛ "enabled by default" |
| Terraform در CI | Push با کار 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 آمدهاند.
# 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"}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 CD | Flux |
|---|---|---|
| وضعیت Sync | argocd_app_info{sync_status} | gotk_resource_info{ready} از KSM |
| سلامت | argocd_app_info{health_status} | Ready همراه دلیل |
| هزینهٔ Reconciliation | argocd_app_reconcile | gotk_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 نوشته شده است.
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 از CI | CI، Commit یا PR میسازد؛ Agent، Apply میکند |
| cluster-admin در CI | اعتبارنامهٔ Cluster در CI نباشد؛ اگر تحریک Sync لازم است Token محدود Project در Argo CD |
| Config در App repo | Config repository یا ارجاع از آن به App repo بهعنوان Base |
| شاخهٔ هر محیط | پوشهٔ هر محیط روی main |
latest در Git | Tag انتشار و Digest؛ نوشتن با Image automation |
Project با نام default | AppProject هر تیم؛ ApplicationSet فقط برای مدیر |
راهحل: کار Deploy را حذف کنید، به CI فقط Token محدود Config repo بدهید و تستهای Repository زیر را اضافه کنید.
سازوکار (Mechanics)
یک Reconciliation در Argo CD، گامبهگام
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، گامبهگام
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.reconciliation | argocd-cm | 120s با 60s نوسان | بازهٔ Poll گیت؛ 0 آن را خاموش میکند که توصیه نمیشود |
--self-heal-timeout-seconds | application-controller | 5 | تأخیر پیش از Sync خودترمیمی |
ARGOCD_SYNC_WAVE_DELAY | Environment کنترلگر | 2 s | مکث میان Waveها |
application.resourceTrackingMethod | argocd-cm | annotation | تشخیص مالکیت منابع توسط Argo CD |
requeueAfterSeconds | مولد ApplicationSet | Git برابر 180 s، PR برابر 1800 s | Poll مولد |
revisionHistoryLimit | Application | 10 | ورودیهای argocd app rollback |
syncWindows | AppProject | allow/deny و cron | پنجرهٔ مجاز تغییر |
.spec.interval | هر شیء Flux | مثلاً 10m | آهنگ Reconciliation و Drift |
.spec.retryInterval | Kustomization | برابر interval | تلاش پس از شکست |
.spec.timeout | Kustomization، HelmRelease | مثلاً 5m | سقف زمان Build/Apply/Health |
--no-cross-namespace-refs | Controllerهای Flux | false | محدودسازی مستاجرها |
--no-remote-bases | kustomize-controller | false | منع Base دوردست Kustomize |
driftDetection.mode | HelmRelease | اختیاری؛ warn یا enabled | تشخیص یا اصلاح Drift در Helm |
update.strategy | ImageUpdateAutomation | Setters | بازنویسی بر پایهٔ نشانگر |
دلیل وضعیتها و پیامهایی که میبینید
| پیام یا دلیل، عین مستندات | ابزار | معنی | راهحل |
|---|---|---|---|
the server could not find the requested resource | Argo CD | CR که CRD آن در Cluster یا Sync نیست | CRD در Wave زودتر یا SkipDryRunOnMissingResource=true |
ComparisonError ... doesn't match $setElementOrder list | Argo CD | کلید تکراری در Merge list مانند متغیر محیطی | حذف تکرار در Manifest |
kustomization path not found: stat /tmp/kustomization-.../invalid: no such file or directory با ArtifactFailed | Flux | .spec.path نادرست | اصلاح مسیر؛ تستهای فصل آن را میگیرند |
couldn't find remote ref "refs/heads/invalid" با GitOperationFailed | Flux | شاخه وجود ندارد | اصلاح ref.branch |
DependencyNotReady | Flux | یک dependsOn یا شیء ارجاعشده Ready نیست | ابتدا وابستگی را اصلاح کنید |
referenced ImageRepository does not exist | Flux | ImagePolicy به ImageRepository ناموجود اشاره دارد | آن را در همان Namespace بسازید |
Failed to install after 1 attempt(s) با RetriesExceeded | Flux helm-controller | تلاشهای Remediation تمام شده | خواندن رویداد Helm؛ Revert یا اصلاح Values |
PruneFailed، BuildFailed، HealthCheckFailed، ReconciliationFailed | Flux 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 نبودنش:
# 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 دارند، اما قواعد مدل از رفتار آنها گرفته شده است.
// 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
}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)
}
}// 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- کنار میروند.
// 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 != ""
}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")
}
}// 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 داشته باشد.
// 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
}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")
}
}module academy/gitops-argocd-flux
go 1.24
require gopkg.in/yaml.v3 v3.0.1CI مربوط به Config repository که این تستها را اجرا و OCI artifact امضاشده منتشر میکند:
# 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هایی هستند که رندر میکند:
# 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"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# 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# 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.EOFDecode میکند. مقصدmap[string]anyباشد؛ Map type نامدار همهٔ Mapهای تودرتو را هم همان Type میکند؛ اولین اجرای تست مدل Drift این خطا را گرفت. - Image automation برای Go با Tagهای semver تغییرناپذیر حاصل از
git tagو Tag جدا با پیشوندsha-برای ردیابی بهتر کار میکند؛filterTagsسیاست را به انتشارها محدود میکند.
Laravel
قبل (Before)
اسکریپت استقرار Laravel از CI روی Production، رایج در روش Push:
# 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 را میسنجد.
# 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"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: httpapiVersion: 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# 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# 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: 2Smoke 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
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
// 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 و اصلاح Drift | selfHeal: true؛ بازهٔ Flux | پیکربندی تکافتاده باقی نمیماند | رخداد نیازمند Suspend است |
| Manifest حذف میشود ولی منبع اجرا میماند | Prune | prune: true و استثنای Prune=false | Namespace تمیز | Commit بد ممکن است حذف کند؛ محافظ allowEmpty |
| Migration با Rollout رقابت میکند | Hook یا Job مرتب | PreSync Job، --isolated، Expand/Contract | یک اجرا در هر انتشار | شکست Hook مانع Deploy |
| هر محیط چندین فایل YAML میخواهد | ApplicationSet یا پوشهٔ Cluster | Matrix حاصل Git × Cluster | برنامهٔ تازه یعنی پوشهٔ تازه | قالب فقط برای مدیر |
| Staging از انتشار عقب میماند | Image automation | Flux ImageUpdateAutomation یا Image Updater | حذف تغییر دستی Tag | ربات با حق نوشتن Git |
| Prod نیازمند تأیید است | Promotion با PR | Automation به شاخه یا PR از CI | بازبینی همان سابقهٔ تغییر | کندتر |
| Rollback | git revert | Revert کردن Commit ارتقا | Git و Cluster هماهنگ | Migration داده برنمیگردد |
| تحویل کند | Webhook | /api/webhook در Argo CD، Receiver در Flux | در حد ثانیه | ارائهٔ Endpoint وبهوک |
| Secrets در Git | SOPS / Sealed Secrets / ESO | Secrets | بدون متن ساده | مدیریت کلید |
| نوسان HPA | Ignore یا حذف replicas | ignoreDifferences، 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 CD | UI داخلی، Dex/OIDC، Casbin RBAC و AppProject |
| یک نمونهٔ مرکزی برای چند Cluster | Argo CD | مدل Hub با Cluster ثبتشده |
| هر Cluster مستقل و بدون نیاز به UI | Flux | Agent هر Cluster؛ فقط Kubernetes RBAC |
| استفادهٔ زیاد از Chart بیرونی با Hook و Test | Flux؛ یا Argo CD با آگاهی از نگاشت Hookها | انتشار واقعی Helm و Remediation |
| Image automation بدون پروژهٔ اضافه | Flux | Controllerها در همان Toolkit |
| Preview برای PR | Argo CD | Pull 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 / preview | CI، Tag را با kustomize.images در Application یا PR generator تنظیم میکند |
| staging | Image automation به main، Commit میکند |
| prod | PR ارتقا از ربات، 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 چنین پیش میرود:
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؛ یک تیم و یک Cluster | Config repo بهشکل Monorepo و Overlay هر محیط | یک Argo CD یا Flux | Image automation به Staging، PR به Prod |
| 10x؛ چند تیم و 2-5 Cluster | repo هر تیم یا CODEOWNERS؛ ApplicationSet و مستاجر | Argo CD HA با Project یا Flux هر Cluster با Multi-tenancy | Webhook، Sync window، اعلان و هشدار OutOfSync |
| 100x؛ مجموعهٔ بزرگ و مناطق متعدد | clusters/<name> ساختهشده از برچسب Cluster؛ OCI artifacts | Argo CD تقسیمشده یا Flux هر Cluster؛ Kargo برای Promotion | Artifact امضاشده، 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ها؛ اجراشده روی میزبان
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 پیشنمایش انجام میدهند. این بخش روی میزبان اجرا شده است:
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#!/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؛ اجراشده روی میزبان
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 تغییر دهید و دوباره اجرا کنید. این آزمایش روی میزبان انجام و سپس تغییر برگردانده شده است:
--- 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 که قبلاً متعلق به برنامه بوده است.
# 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=1Digest اینجا کوتاه شده؛ خروجی ذخیرهشده مقدار کامل را دارد. Service با وجود دوازده فیلد اضافی در شیء زنده Synced است. هفت Replica حتی بدون -ignore گزارش نمیشود، چون Base فیلد replicas ندارد؛ بدون Flag هم همان خروجی را میگیرید. kube-root-ca.crt گزارش نمیشود چون هیچچیز آن را رهگیری نمیکند. RequiresPruning برچسب این مدل است؛ Argo CD برنامه را OutOfSync و منبع را نیازمند Prune نشان میدهد.
۴. ویرایش برای Promotion؛ اجراشده روی میزبان روی کپی موقت
# 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؛ مورد انتظار، اجرا نشده
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 روی برنامهٔ زنده؛ مورد انتظار، اجرا نشده
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؛ مورد انتظار، اجرا نشده
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 در برابر دکمه؛ مورد انتظار، اجرا نشده
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 و Pull | CI در Git مینویسد؛ Agent داخل Cluster، Apply میکند؛ اعتبارنامهٔ Cluster در CI نیست |
| چیدمان (Layout) | Config repo، فقط main، Overlay هر محیط، CODEOWNERS روی Prod |
| اجزای Argo CD | api-server برای UI/CLI/RBAC/Webhook؛ repo-server برای رندر؛ application-controller برای Diff/Sync؛ Redis برای Cache |
| سیاست Sync | automated + 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 |
| ApplicationSet | Matrix حاصل Git × Cluster؛ PR generator برای Preview؛ فقط مدیر |
| اشیای Flux | GitRepository/OCIRepository سپس Kustomization/HelmRelease؛ Provider/Alert/Receiver |
| Image automation | ImageRepository سپس 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-server | argocd-server: رابط gRPC/REST، UI، RBAC، SSO و Webhook |
| repo-server | مؤلفهٔ Argo CD برای Clone و رندر Manifest |
| application-controller | Controller مقایسه و Sync کردن Applicationها |
| Redis | Cache دورریختنی 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 apps | Application که Manifestهایش Application هستند |
| Argo CD RBAC | سیاستهای Casbin در argocd-rbac-cm |
| ورود یکپارچه (SSO) | ورود از طریق Dex یا ارائهدهندهٔ OIDC |
| Argo CD Notifications | Triggerها، قالبها و سرویسها در argocd-notifications-cm |
| Argo CD Image Updater | Controller تغییر Tag تصویر برنامههای Argo CD با ImageUpdater CR |
| Flux | Toolkit کنترلگرهای GitOps در CNCF |
| source-controller | دریافت منابع Git/OCI/Helm/Bucket بهشکل Artifact |
| kustomize-controller | ساخت و Apply کردن Kustomization، Prune و رمزگشایی SOPS |
| helm-controller | اجرای Helm release برای اشیای HelmRelease |
| notification-controller | Webhook ورودی با 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 در Flux | CRD اعمال مسیر یک منبع؛ با فایل kustomization.yaml متفاوت است |
| HelmRelease | CRD در Flux برای Helm release |
| dependsOn | ترتیب میان Kustomizationها یا HelmReleaseها در Flux |
| بررسی سلامت (Health checks) | healthChecks / wait در Flux روی اشیای Applyشده |
| Receiver | Endpoint وبهوک 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 |
نشانگر $imagepolicy | Comment در 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 آن |
| Kargo | Platform ارتقا با Warehouse، Freight، Stage و Promotion |
| بازگشت با Revert (Rollback by revert) | git revert تغییر و سپس Sync توسط Agent |
| argocd app rollback | Sync دوبارهٔ ورودی قدیمی تاریخچهٔ Application |
| Argo Rollouts | Controller تحویل تدریجی با Canary و Blue-green |
| Flagger | Operator تحویل تدریجی برای Mesh/Ingress |
| Crossplane | چارچوب Control plane برای مدیریت منابع ابر از طریق CRD |
| tf-controller یا Tofu Controller | Controller در 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)
- OpenGitOps: اصول https://opengitops.dev/ — متن اصول v1.0.0 https://raw.githubusercontent.com/open-gitops/documents/main/PRINCIPLES.md — واژهنامه https://raw.githubusercontent.com/open-gitops/documents/main/GLOSSARY.md — انتشارها https://github.com/open-gitops/documents/releases
- Argo CD: مرور https://argo-cd.readthedocs.io/en/stable/ — شروع کار https://argo-cd.readthedocs.io/en/stable/getting_started/ — مفاهیم اصلی https://argo-cd.readthedocs.io/en/stable/core_concepts/ — معماری https://argo-cd.readthedocs.io/en/stable/operator-manual/architecture/ — پیکربندی اعلانی https://argo-cd.readthedocs.io/en/stable/operator-manual/declarative-setup/ — مشخصات Application https://argo-cd.readthedocs.io/en/stable/user-guide/application-specification/ — دسترسپذیری بالا https://argo-cd.readthedocs.io/en/stable/operator-manual/high_availability/
- همگامسازی Argo CD: همگامسازی خودکار https://argo-cd.readthedocs.io/en/stable/user-guide/auto_sync/ — گزینههای Sync https://argo-cd.readthedocs.io/en/stable/user-guide/sync-options/ — Wave و Hook https://argo-cd.readthedocs.io/en/stable/user-guide/sync-waves/ — Hook منابع https://argo-cd.readthedocs.io/en/stable/user-guide/resource_hooks/ — پنجرههای Sync https://argo-cd.readthedocs.io/en/stable/user-guide/sync_windows/ — سلامت https://argo-cd.readthedocs.io/en/stable/operator-manual/health/ — محاسبهٔ Diff https://argo-cd.readthedocs.io/en/stable/user-guide/diffing/ — رهگیری منابع https://argo-cd.readthedocs.io/en/stable/user-guide/resource_tracking/ — راهبردهای رهگیری https://argo-cd.readthedocs.io/en/stable/user-guide/tracking_strategies/ — منابع OCI https://argo-cd.readthedocs.io/en/stable/user-guide/oci/ — وبهوکها https://argo-cd.readthedocs.io/en/stable/operator-manual/webhook/ — پرسشهای رایج https://argo-cd.readthedocs.io/en/stable/faq/ — روشهای توصیهشده https://argo-cd.readthedocs.io/en/stable/user-guide/best_practices/
- Argo CD ApplicationSet: معرفی https://argo-cd.readthedocs.io/en/stable/operator-manual/applicationset/ — مولدها https://argo-cd.readthedocs.io/en/stable/operator-manual/applicationset/Generators/ — Git https://argo-cd.readthedocs.io/en/stable/operator-manual/applicationset/Generators-Git/ — Cluster https://argo-cd.readthedocs.io/en/stable/operator-manual/applicationset/Generators-Cluster/ — Matrix https://argo-cd.readthedocs.io/en/stable/operator-manual/applicationset/Generators-Matrix/ — Pull request https://argo-cd.readthedocs.io/en/stable/operator-manual/applicationset/Generators-Pull-Request/ — امنیت https://argo-cd.readthedocs.io/en/stable/operator-manual/applicationset/Security/ — Bootstrap خوشه با app of apps https://argo-cd.readthedocs.io/en/stable/operator-manual/cluster-bootstrapping/
- دسترسی و عملیات Argo CD: پروژهها https://argo-cd.readthedocs.io/en/stable/user-guide/projects/ — RBAC https://argo-cd.readthedocs.io/en/stable/operator-manual/rbac/ — مدیریت کاربر و SSO https://argo-cd.readthedocs.io/en/stable/operator-manual/user-management/ — اعلانها https://argo-cd.readthedocs.io/en/stable/operator-manual/notifications/ — Triggerها https://argo-cd.readthedocs.io/en/stable/operator-manual/notifications/triggers/ — قالبها https://argo-cd.readthedocs.io/en/stable/operator-manual/notifications/templates/ — فهرست https://argo-cd.readthedocs.io/en/stable/operator-manual/notifications/catalog/ — Slack https://argo-cd.readthedocs.io/en/stable/operator-manual/notifications/services/slack/ — سنجهها https://argo-cd.readthedocs.io/en/stable/operator-manual/metrics/ —
argocd app rollbackhttps://argo-cd.readthedocs.io/en/stable/user-guide/commands/argocd_app_rollback/ — انتشارها https://github.com/argoproj/argo-cd/releases - Argo CD Image Updater: مرور https://argocd-image-updater.readthedocs.io/en/stable/ — روشهای بهروزرسانی https://argocd-image-updater.readthedocs.io/en/stable/basics/update-methods/ — راهبردها https://argocd-image-updater.readthedocs.io/en/stable/basics/update-strategies/ — برنامهها https://argocd-image-updater.readthedocs.io/en/stable/configuration/applications/ — تصویرها https://argocd-image-updater.readthedocs.io/en/stable/configuration/images/
- Flux: مفاهیم https://fluxcd.io/flux/concepts/ — مؤلفهها https://fluxcd.io/flux/components/ — منبع https://fluxcd.io/flux/components/source/ — GitRepository https://fluxcd.io/flux/components/source/gitrepositories/ — OCIRepository https://fluxcd.io/flux/components/source/ocirepositories/ — kustomize-controller https://fluxcd.io/flux/components/kustomize/ — Kustomization https://fluxcd.io/flux/components/kustomize/kustomizations/ — helm-controller https://fluxcd.io/flux/components/helm/ — HelmRelease https://fluxcd.io/flux/components/helm/helmreleases/
- اعلانها و تصویرها در Flux: notification-controller https://fluxcd.io/flux/components/notification/ — Alerts https://fluxcd.io/flux/components/notification/alerts/ — Providers https://fluxcd.io/flux/components/notification/providers/ — Receivers https://fluxcd.io/flux/components/notification/receivers/ — کنترلگرهای تصویر https://fluxcd.io/flux/components/image/ — ImageRepository https://fluxcd.io/flux/components/image/imagerepositories/ — ImagePolicy https://fluxcd.io/flux/components/image/imagepolicies/ — ImageUpdateAutomation https://fluxcd.io/flux/components/image/imageupdateautomations/
- راهنماهای Flux: بهروزرسانی تصویر https://fluxcd.io/flux/guides/image-update/ — ساختار Repository https://fluxcd.io/flux/guides/repository-structure/ — SOPS https://fluxcd.io/flux/guides/mozilla-sops/ — Sealed اسرار https://fluxcd.io/flux/guides/sealed-secrets/ — گیرندههای Webhook https://fluxcd.io/flux/guides/webhook-receivers/ — سنجهها https://fluxcd.io/flux/monitoring/metrics/ — سنجههای سفارشی https://fluxcd.io/flux/monitoring/custom-metrics/ — مصنوعهای OCI https://fluxcd.io/flux/cheatsheets/oci-artifacts/ — اکشن GitHub https://fluxcd.io/flux/flux-gh-action/ — پرسشهای رایج https://fluxcd.io/flux/faq/
- نصب Flux: Bootstrap برای GitHub https://fluxcd.io/flux/installation/bootstrap/github/ — چندمستاجری https://fluxcd.io/flux/installation/configuration/multitenancy/ — امنیت https://fluxcd.io/flux/security/ —
flux installhttps://fluxcd.io/flux/cmd/flux_install/ —flux push artifacthttps://fluxcd.io/flux/cmd/flux_push_artifact/ — انتشارها https://github.com/fluxcd/flux2/releases — تاریخچهٔ Flux v1 https://raw.githubusercontent.com/fluxcd/flux/master/README.md - CNCF: فارغالتحصیلی Argo https://www.cncf.io/announcements/2022/12/06/the-cloud-native-computing-foundation-announces-argo-has-graduated/ — فارغالتحصیلی Flux https://www.cncf.io/announcements/2022/11/30/flux-graduates-from-cncf-incubator/
- Kargo: مستندات https://docs.kargo.io/ — مفاهیم اصلی https://docs.kargo.io/user-guide/core-concepts/
- تحویل تدریجی: Argo Rollouts https://argoproj.github.io/argo-rollouts/ — Flagger https://docs.flagger.app/
- زیرساخت: Crossplane https://docs.crossplane.io/latest/whats-crossplane/ — Tofu Controller README https://raw.githubusercontent.com/flux-iac/tofu-controller/main/README.md — مستندات Tofu Controller https://flux-iac.github.io/tofu-controller/ — شروع کار https://flux-iac.github.io/tofu-controller/getting_started/
- اسرار: SOPS https://raw.githubusercontent.com/getsops/sops/main/README.rst — Sealed اسرار https://raw.githubusercontent.com/bitnami-labs/sealed-secrets/main/README.md — External اسرار Operator https://external-secrets.io/latest/
- Laravel 13: استقرار و Route سلامت https://laravel.com/docs/13.x/deployment — Migrationها (
--force,--isolated) https://laravel.com/docs/13.x/migrations - اکشنهای GitHub استفادهشده: checkout https://raw.githubusercontent.com/actions/checkout/main/README.md — setup-go https://raw.githubusercontent.com/actions/setup-go/main/README.md — cosign-installer https://raw.githubusercontent.com/sigstore/cosign-installer/main/README.md — اکشن Flux https://raw.githubusercontent.com/fluxcd/flux2/main/action/README.md
- فیلد تصویرها در Kustomize: https://kubectl.docs.kubernetes.io/references/kustomize/kustomization/images/