← Back to blogs

8 Infrastructure as Code Examples for Modern Platforms

June 7, 2026CloudCops

infrastructure as code examples
Terraform examples
GitOps
Policy as Code
DevOps
8 Infrastructure as Code Examples for Modern Platforms

The search for infrastructure as code examples often begins when a familiar pain shows up. Dev and production don't match. Someone changed a security group in the console. A rollout worked in one region and failed in another. The repo has a main.tf, but nobody trusts it as the full truth of the platform anymore.

That's the gap between demo IaC and production IaC.

Infrastructure as code works because it defines desired state in version-controlled automation, so teams can reproduce environments consistently and review infrastructure changes like application code. That model is now standard enough that it's routinely tied into CI/CD and Git-based change management, with tools such as Terraform, AWS CloudFormation, Ansible, and Pulumi used to provision and update infrastructure through code, as outlined in Coursera's overview of IaC practices. It's also become a mainstream platform capability, not a niche trick. One market report valued the global Infrastructure as Code market at USD 0.8 billion in 2022 and projected USD 2.3 billion by 2027, a 24.0% CAGR.

That growth matters because teams aren't asking whether to automate infrastructure anymore. They're asking how to make it reviewable, safe, portable, and recoverable under pressure. That's also why learning these patterns is an essential practice for AWS DevOps certification.

The examples below move past isolated snippets. They show integrated patterns that combine infrastructure, policy, GitOps, and observability into a version-controlled operating model.

1. Terraform Module Pattern with Remote State Backend

A single flat Terraform folder works for a proof of concept. It breaks down when multiple teams touch shared infrastructure, environments diverge, and nobody knows which change last modified the state.

The better pattern is modular Terraform with remote state as the control plane for collaboration. Networking, compute, database, DNS, and monitoring become separate reusable modules. Environment composition lives above them. State moves out of a local file and into a backend with locking and encryption, so the team has one source of truth instead of several laptops pretending to be one.

A diagram illustrating Terraform infrastructure modules, remote state storage in cloud buckets, and Git repository versioning.

What good structure looks like

One practical Terraform adoption case moved away from manual, inconsistent changes by centralizing all environments into a single repo with an environments/{dev,stg,prod} structure plus shared modules for networking, compute, storage, DNS, and monitoring, as described in this Terraform drift case study. That's the shape I trust in production because it separates reuse from environment intent.

Remote state matters as much as module design. If your team shares code but not state safely, you'll still get collisions, hidden drift, and “works on my branch” infrastructure.

  • Pin module versions: Reference git tags or registry versions explicitly. Floating versions make root modules unpredictable.
  • Keep inputs explicit: Prefer variables over deep chains of data sources. Modules are easier to test when dependencies are visible.
  • Validate before merge: Run terraform fmt, terraform validate, and tflint in pre-commit and CI.

Practical rule: Remote state isn't just storage. It's a concurrency and trust boundary.

What fails in real environments

The most common failure is over-abstracting too early. Teams build a “universal” VPC module or database module that hides cloud-specific behavior so aggressively that no one can reason about what will happen.

The second failure is casual treatment of state. If you want a deeper look at how teams should manage locking, sensitivity, and recovery, study Terraform state files in production. State is operational data. Handle it like one of your most sensitive system assets.

2. Terragrunt DRY Infrastructure with Dependency Management

Terraform modules solve reuse. They don't solve repetition across dozens of nearly identical environment stacks. That's where Terragrunt earns its place.

If you've ever copied the same backend config, provider settings, naming rules, and common variables into dev, staging, and production folders, you already know the problem. Terragrunt removes that duplication by letting teams define shared settings once and inherit them down a directory tree.

Where Terragrunt fits best

Terragrunt works well when the platform shape is mostly consistent across environments, but values and dependency wiring differ. A common structure is modules/ for reusable Terraform and live/ for environment-specific Terragrunt configuration. That keeps business logic in Terraform and orchestration logic in Terragrunt.

The primary gain isn't fewer lines of HCL. It's clearer operational intent. Dependency blocks make ordering explicit, and inherited settings reduce the chances that one environment drifts because someone forgot to copy a backend or provider update.

Terragrunt is most useful when your problem is coordination across environments, not when your problem is lack of Terraform discipline.

How to keep it maintainable

A few habits make Terragrunt hold up under scale.

  • Use parent inheritance carefully: find_in_parent_folders() is powerful, but keep the inheritance chain shallow enough that engineers can trace it without detective work.
  • Define dependency contracts: Use dependency blocks for outputs between networking, cluster, and application layers. Avoid hidden coupling through naming assumptions.
  • Validate at the stack level: Run terragrunt validate-all early in CI so you catch structural issues before plans start failing one by one.

Terragrunt can become a mess if teams treat it like a second programming language. Keep it thin. If the orchestration layer starts carrying too much business logic, debugging gets harder and upgrades get slower.

3. OpenTofu Drop-In Terraform Alternative with Open Source Guarantee

Sometimes the best infrastructure as code examples aren't about a different architecture. They're about preserving the same architecture while changing the governance model behind it.

That's the OpenTofu case. If your team already runs Terraform modules, remote state, pull request workflows, and provider-based provisioning, OpenTofu lets you keep that operating pattern while choosing an open-source path.

Why teams choose it

The architectural appeal is straightforward. You don't have to redesign your repo, your modules, or your promotion process just to reduce dependence on one vendor's direction. For organizations with open-source mandates, procurement constraints, or long-lived platform investments, that matters.

OpenTofu fits especially well in estates where Terraform is already embedded, but leadership wants stronger control over licensing risk and long-term portability. That's not ideology. It's platform risk management.

A practical adoption pattern is to trial it first in a non-production stack that already has clean module boundaries and disciplined state handling. If your current Terraform estate is messy, OpenTofu won't fix that. It will inherit it.

Trade-offs people skip in migration discussions

Compatibility makes migration easier, but it can also create false confidence. Teams assume “drop-in replacement” means “no architectural review needed.” That's rarely true.

  • Check provider behavior: The syntax may be familiar, but provider versions and edge cases still deserve testing.
  • Keep the same state discipline: Reuse the same remote backend and locking pattern to avoid introducing migration noise.
  • Write down the decision: An architecture decision record helps future teams understand why portability or governance mattered.

The underserved question in many infrastructure as code examples is when a tool choice stops being about syntax and starts being about governance. That gap shows up clearly in Scale Computing's discussion of IaC as a broader operational strategy, especially for multi-team and regulated environments.

4. Policy-as-Code with OPA Gatekeeper and Rego Rules

Provisioning examples usually end right before the dangerous part. The cluster exists. The namespace exists. The ingress exists. Then somebody deploys an image from an unapproved registry, skips labels, or opens traffic wider than intended.

Policy-as-code closes that gap.

OPA Gatekeeper lets teams codify platform rules as admission controls. Instead of relying on tribal knowledge, you express what's allowed and what's rejected. Rego becomes the language for organizational intent, and Kubernetes becomes the enforcement point.

A hand-drawn illustration showing a Kubernetes gatekeeper knight enforcing Rego policies on infrastructure resources.

Start with the rules that prevent expensive mistakes

Good first policies are boring by design. Require labels. Restrict image registries. Enforce namespace boundaries. Block privileged containers unless there's an approved exception path.

That approach matches a bigger gap in the market. Many example-heavy articles still focus on first-deploy templates but rarely show how teams handle drift detection, policy checks, rollback workflows, or secrets once systems are live, a weakness highlighted in Lumenalta's analysis of what most IaC examples miss.

  • Begin in audit mode: Let teams see violations before you block deployments.
  • Test policies like code: Rego without tests turns governance into guesswork.
  • Parameterize constraints: Teams need controlled flexibility, not one giant hard-coded rule file.

Field note: The best policy programs don't start broad. They start with a few rules nobody should be arguing about.

Enforcement belongs in delivery, not in a PDF

A mature pattern checks policy before merge, during CI, and again at cluster admission. That layered model catches issues early and still protects the runtime. If you only enforce at the cluster, developers learn late. If you only enforce in CI, console changes and side channels still slip through.

For teams building secure platform workflows, policy as code in DevSecOps pipelines is where governance becomes operational instead of aspirational. It's also central to streamlining DevSecOps on Azure and similar multi-team cloud setups.

5. GitOps Deployment Pattern with ArgoCD and Git as Source of Truth

GitOps is one of the few patterns that becomes more valuable as complexity rises. In small systems, it feels disciplined. In large systems, it becomes survival.

ArgoCD watches Git and reconciles the cluster toward what's declared there. That sounds simple, but the operational consequence is huge. Engineers stop treating kubectl apply from a laptop as an acceptable deployment model. The cluster changes because Git changed, not because someone had shell access and good intentions.

A diagram illustrating GitOps workflow with Argo CD, Kubernetes cluster, and continuous reconciliation of application states.

Why GitOps works under pressure

A strong GitOps setup creates review history, rollback points, and a visible desired state. That lines up with a key finding from an academic IaC adoption study, which reported that IaC improves stability, repeatability, and knowledge of cloud environments because infrastructure is documented, tested, and deployed automatically through version control, creating a visible deployment history. The same study noted that when the code is ready, resources can be re-created “with a click of a button” after failure or breaking change, as described in the Theseus study on IaC adoption.

That recovery mindset is why GitOps belongs in any serious platform architecture. It's not only a deployment style. It's an incident response capability.

How teams make ArgoCD production-ready

The weak version of GitOps is “put YAML in Git.” The stronger version adds structure and guardrails.

  • Separate concerns clearly: Keep app manifests, cluster add-ons, and platform-level policies in repos or folders with obvious ownership.
  • Encrypt secrets before Git sees them: Use SOPS, Sealed Secrets, or an external secrets operator. Plaintext secrets in a GitOps workflow are an own goal.
  • Use sync waves and hooks deliberately: Database migrations and dependency ordering need explicit handling.

Where GitOps often disappoints is around unclear repository design. If every team invents its own structure, ArgoCD becomes a deployment engine without a platform standard. Standardize layout early.

6. Helm Charts with Values Templating for Multi-Environment Kubernetes Deployments

Helm is often described as a package manager for Kubernetes, but that undersells its real production value. Helm is a standardization layer.

When teams package deployment patterns as charts, they stop copying YAML and start reusing approved release shapes. The same chart can drive dev, staging, and production through values files, while preserving a consistent manifest structure.

What Helm does well

Helm works best for packaging repeatable application and platform components. Internal application charts, ingress controllers, external DNS, Prometheus, Grafana, Loki, PostgreSQL, and RabbitMQ are all common examples. The strength isn't just templating. It's the combination of versioning, packaging, and rollback support.

That makes Helm especially useful inside a GitOps model. ArgoCD can reconcile Helm-based applications, while platform teams define baseline chart conventions that product teams consume.

A chart should encode a deployment standard, not become a dumping ground for every environment-specific exception.

What breaks chart quality

The most common mistake is making charts too clever. Highly nested conditionals, sprawling values files, and generic helper templates create charts that only their authors can debug.

A more durable approach looks like this:

  • Keep values hierarchy simple: Use a base values.yaml and small environment overlays such as values-dev.yaml or values-prod.yaml.
  • Render locally before shipping: helm template catches many mistakes before a controller does.
  • Version charts explicitly: Tie chart releases to clear changes in deployment behavior, not just application image tags.

When teams outgrow raw YAML but aren't ready for a full internal platform abstraction, Helm is often the right middle layer. It gives enough structure to scale without hiding Kubernetes so much that nobody understands the output.

7. Observability-as-Code Pattern with OpenTelemetry, Prometheus, Grafana, and Loki

A surprising number of infrastructure as code examples build the platform and ignore the evidence you'll need when it fails. That's backward. If the stack isn't observable by default, operations remain partly manual no matter how elegant the provisioning code looks.

Observability-as-code fixes that by declaring telemetry infrastructure, dashboards, alert rules, and log pipelines in version control alongside the platform itself. OpenTelemetry standardizes instrumentation. Prometheus handles metrics. Grafana visualizes and alerts. Loki manages logs. The exact packaging may use Helm, Terraform, or both.

The pattern that actually helps operators

The useful pattern is layered. Platform teams define collectors, scrape configs, retention settings, alert routes, and baseline dashboards. Application teams add service-specific metrics and tracing spans inside a known framework. That split gives consistency without blocking service-level ownership.

Here, “everything as code” stops being a slogan. If alert rules live in a UI, dashboards drift, and scrape configs get changed manually, your incident response posture is only partly reproducible.

  • Version alerting rules with the services they protect: Ownership stays close to the domain.
  • Template dashboards carefully: One reusable dashboard per service class is better than dozens of near-duplicates.
  • Control telemetry cost intentionally: Collect what engineers will use. Don't index or retain everything by default.

What mature teams do differently

They wire observability into delivery. New services land with dashboards, alerts, and trace pipelines already defined. Rollouts can query those signals. Platform reviews include telemetry standards, not just CPU and memory requests.

The operational gain is less about dashboards than about confidence. Teams can roll forward or roll back faster when every deployment already emits the signals needed for verification.

8. Progressive Delivery Pattern with Argo Rollouts and Canary Deployments

If GitOps answers “how should desired state reach the cluster,” progressive delivery answers “how should risky change reach users.”

Argo Rollouts extends Kubernetes deployment behavior with canary, blue-green, and analysis-driven release strategies. Instead of flipping all traffic at once, teams shift it in controlled steps and watch real signals before continuing.

Why this pattern belongs with IaC

Progressive delivery is often treated as application delivery, not infrastructure as code. In practice, it belongs here because rollout rules, traffic policies, analysis templates, and rollback conditions are all declarative artifacts. They can be reviewed, versioned, promoted, and rolled back like any other operational code.

That makes it a natural partner to GitOps and observability-as-code. Git declares the rollout. ArgoCD syncs it. Argo Rollouts executes it. Prometheus or another signal source evaluates health. The release process becomes a controlled system instead of a human ceremony.

A good technical walkthrough helps clarify the moving parts. For teams working through production-safe release mechanics, zero-downtime deployment strategies is the right adjacent discipline.

Here's a practical video primer before going deeper into rollout design.

What separates safe canaries from theater

A canary only works if the verification logic is trustworthy. If your metrics are noisy, missing, or too delayed, traffic shifting becomes automation theater.

  • Start with simple steps: Use a small canary slice, hold, evaluate, then continue.
  • Measure service behavior, not only infrastructure health: Error rates, latency, and dependency failures matter more than pod readiness alone.
  • Define rollback conditions in code: Manual judgment still matters, but the baseline safety net should already exist.

“If your rollback depends on someone noticing a graph in time, you don't have progressive delivery. You have hope with YAML.”

8-Point Infrastructure-as-Code Comparison

PatternImplementation complexity 🔄Resource requirements ⚡Expected outcomes 📊Ideal use cases 💡Key advantages ⭐
Terraform Module Pattern with Remote State BackendModerate → High: module design + state management and migrationModerate: remote backend (S3/Blob/Terraform Cloud), CI/CD, backupsReusable, versioned, portable infra; single source of truthMulti-cloud projects, teams needing reproducible infra and complianceModule reuse, state locking, CI integration, cross-cloud portability
Terragrunt DRY Infrastructure with Dependency ManagementModerate: additional abstraction and hierarchical configsLow–Moderate: repo layout, terragrunt.hcl, CI checksDRY multi-environment deployments, consistent ordering and outputsLarge multi-env/multi-account orgs with repeated stacksEliminates boilerplate, automatic dependency ordering, rapid env creation
OpenTofu Drop-In Terraform Alternative with OpenSource GuaranteeLow → Moderate: drop-in replacement but governance for transitionLow: same tooling as Terraform; community engagement for providersVendor-independent, MPL2 open-source compatibility with Terraform stateRegulated organizations and teams avoiding license lock-inZero migration effort, open governance, community-driven development
Policy-as-Code with OPA Gatekeeper and Rego RulesHigh: authoring Rego policies and Gatekeeper admission controlsModerate–High: Gatekeeper HA, policy testing infra, CI integrationAutomated enforcement, fewer policy violations, robust audit trailsSecurity-first orgs, regulated industries, multi-tenant Kubernetes platformsPrevents non-compliant deployments, centralized policy reuse, auditable enforcement
GitOps Deployment Pattern with ArgoCD and Git as Source of TruthModerate: paradigm shift to declarative workflows and Git opsModerate: ArgoCD control plane, repo management, secret toolingContinuous reconciliation, instant rollbacks, strong auditabilityKubernetes-centric teams, platform engineering, regulated deploymentsSingle source of truth, automatic sync, rollback and RBAC-enabled audit trail
Helm Charts with Values Templating for Multi-Environment Kubernetes DeploymentsModerate: templating complexity and values managementLow–Moderate: chart repositories, CI, chart testing toolsParameterized, versioned deployments across environments; rollbacksApp packaging on Kubernetes, teams standardizing manifestsWidely adopted ecosystem, templating reuse, release history and rollback
Observability-as-Code Pattern with OpenTelemetry, Prometheus, Grafana, and LokiHigh: instrumentation, query languages, and stack orchestrationHigh: storage, compute, retention planning, dashboard codeFaster MTTD/MTTR, unified metrics/logs/traces, reproducible monitoringLarge distributed systems, SRE teams, compliance-driven orgsVendor-neutral telemetry, correlated debugging, code-defined dashboards
Progressive Delivery Pattern with Argo Rollouts and Canary DeploymentsHigh: rollout strategies, metric analysis, and service-mesh integrationModerate–High: observability, service mesh or advanced traffic controlReduced deployment risk, automatic metric-driven rollbacks, safe experimentsHigh-traffic services, feature experimentation, teams needing low change-failure ratesMetric-driven canaries, zero-downtime rollouts, automated rollback and A/B testing

Unifying Your Stack with an Everything-as-Code Ethos

The strongest infrastructure as code examples don't live in isolation. A Terraform module library without policy still allows unsafe patterns. GitOps without observability still leaves operators guessing. Helm without governance becomes a templating sprawl. Progressive delivery without good telemetry is just staged risk.

The useful shift is to think in connected control loops.

Terraform or OpenTofu defines cloud foundations and shared platform components. Terragrunt coordinates those definitions across environments. OPA Gatekeeper enforces what may enter the cluster. ArgoCD reconciles workloads from Git. Helm packages repeatable application and platform releases. OpenTelemetry, Prometheus, Grafana, and Loki expose the runtime truth. Argo Rollouts reduces deployment blast radius by evaluating live signals before wider release.

That's the practical meaning of an everything-as-code operating model. Infrastructure, policy, deployment, and observability stop being separate administrative domains and become parts of one version-controlled system.

This also aligns with where the market is heading. Recent industry guidance increasingly frames IaC as a foundational operational strategy for distributed environments rather than just a provisioning convenience. A significant gap in many published examples isn't lack of syntax. It's lack of operational realism. Teams need examples that survive drift, review, rollback, policy enforcement, and incident response, not just first deployment success.

In day-to-day platform work, that changes what “good” looks like. Good IaC isn't the shortest file. It isn't the cleverest module. It isn't a screenshot of a successful apply. Good IaC gives teams a safe path for change. It creates traceability when auditors ask questions. It reduces improvisation during incidents. It allows teams to reproduce environments across regions and accounts without relying on memory.

The architectural payoff is consistency and controlled speed. Changes move through pull requests, policy checks, reconciliation, telemetry, and rollback paths that already exist before the incident starts. That is what makes a platform resilient.

If you're reviewing your own estate, start with one question. Can your team explain how infrastructure is provisioned, governed, deployed, observed, and rolled back using code alone? If the answer is only partial, that's where the next improvement belongs.


CloudCops GmbH helps startups, scale-ups, and enterprise teams turn scattered automation into a coherent platform model. If you need hands-on support with Terraform, Terragrunt, OpenTofu, GitOps, Kubernetes, policy-as-code, or observability-as-code, CloudCops GmbH can co-build the architecture, implement the workflows, and leave your team with code they own and can operate confidently.

Ready to scale your cloud infrastructure?

Let's discuss how CloudCops can help you build secure, scalable, and modern DevOps workflows. Schedule a free discovery call today.

Continue Reading

Read The 5-Layer GitOps Pipeline We Use for Every Enterprise Client
Cover
Mar 2, 2026

The 5-Layer GitOps Pipeline We Use for Every Enterprise Client

How we structure GitOps across infrastructure, platform, security, observability, and application layers — and why treating them as one flat repo doesn't scale.

GitOps
+5
S
Read How We Migrated Apache Kafka from VMs to Kubernetes (AKS)
Cover
Mar 2, 2026

How We Migrated Apache Kafka from VMs to Kubernetes (AKS)

Lessons from migrating a production Kafka cluster, 60+ Elixir microservices, and an entire Ansible-managed infrastructure to Azure Kubernetes Service — including the five things that nearly derailed us.

Kubernetes
+7
S
Read Docker log tail meistern und Container-Logs in Echtzeit analysieren
Cover
Mar 5, 2026

Docker log tail meistern und Container-Logs in Echtzeit analysieren

Lernen Sie, wie Sie Docker log tail effektiv nutzen, um Container-Logs in Echtzeit zu überwachen. Inklusive Praxisbeispiele, Befehle und Expertentipps für 2026.

docker log tail
+4
C