Pidoku

Archive

This learning material is in the archive. It is not currently maintained and has not been updated with the latest information, so tool versions, prices and dates may be out of date.

Infrastructure as Code and GitOps

Module 8 Lesson 8.e 45 min Difficulty 3/5

Prerequisites 8.a

The idea in one minute#

Infrastructure as code (IaC) describes infrastructure — networks, databases, clusters, DNS, IAM — in files that live in version control, are reviewed like code, and are applied by a tool (Terraform/OpenTofu, Pulumi, CloudFormation, Crossplane). You get history, review, repeatable environments, and a way to rebuild after a disaster.

GitOps takes it one step further for what runs on clusters: the Git repository is the single source of truth for the desired state, and an agent in the cluster (Argo CD, Flux) continuously reconciles the live state towards it. Deploying is a merge; rolling back is a revert; drift — someone changing production by hand — is detected and undone automatically.

An analogy#

Building plans filed with the city. A builder works from the approved drawings; any change is a revised drawing, reviewed and stamped. An inspector compares the building to the plans (drift detection). If the building burns down, it can be rebuilt from the file.

A picture#

flowchart LR
  DEV[":i-user: Engineer"] --> PR[":github: <b>Pull request</b><br/><small>review + plan output</small>"]
  PR --> CI[":i-check: <b>CI</b><br/><small>fmt, validate, policy, plan</small>"]
  CI --> MAIN[":i-git-branch: main"]
  MAIN --> TF[":terraform: <b>Terraform apply</b><br/><small>cloud resources</small>"]
  MAIN --> ARGO[":argo: <b>Argo CD / Flux</b><br/><small>reconcile loop</small>"]
  ARGO --> K8S[":kubernetes: <b>Cluster</b>"]
  K8S -.->|"drift detected"| ARGO
  TF --> CLOUD[":i-cloud: <b>Cloud</b>"]
  class DEV neutral
  class PR,CI compute
  class MAIN memory
  class TF,ARGO queue
  class K8S,CLOUD io

How it really works#

Terraform in one page#

hcl
resource "aws_db_instance" "orders" {
  identifier              = "orders-prod"
  engine                  = "postgres"
  engine_version          = "17"
  instance_class          = "db.r7g.xlarge"
  multi_az                = true
  backup_retention_period = 14
  deletion_protection     = true

  lifecycle {
    prevent_destroy = true   # terraform refuses to plan a destroy of this resource
  }
}

The workflow: terraform plan computes the difference between the files, the state (what Terraform believes exists) and reality; a human reviews the plan; terraform apply executes it. (OpenTofu is the open-source fork with the same workflow.)

SRE rules for IaC:

RuleWhy
Review the plan, not just the codeA one-line rename can plan a destroy-and-recreate of a database
Small state files (per service, per environment)A bad apply has a small blast radius; plans are fast
Remote state with lockingTwo applies at once corrupt state
prevent_destroy / deletion protection on stateful resourcesTypos must not delete data
Apply from CI, not laptopsConsistent versions, credentials and audit trail
Policy as code (OPA/Conftest, Sentinel, Checkov, Trivy)Block public buckets, unencrypted volumes, missing tags before apply
Pin provider and module versionsReproducible plans
Stage infrastructure changesApply to staging, then one region, then the rest — infrastructure changes are changes (8.c)
Detect driftScheduled plan that alerts when reality differs from code

GitOps#

The four GitOps principles (OpenGitOps, a CNCF project):

  1. Declarative: the desired state is described, not scripted.
  2. Versioned and immutable: stored in Git with full history.
  3. Pulled automatically: agents pull the desired state; CI does not push credentials into the cluster.
  4. Continuously reconciled: agents observe the actual state and correct differences.

An Argo CD Application:

YAML
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata: { name: checkout, namespace: argocd }
spec:
  project: payments
  source:
    repoURL: https://github.com/example/deploy
    path: apps/checkout/overlays/prod
    targetRevision: main
  destination: { server: https://kubernetes.default.svc, namespace: payments }
  syncPolicy:
    automated: { prune: true, selfHeal: true }   # undo manual changes, delete removed resources
    syncOptions: [CreateNamespace=true]

SRE consequences:

  • Deploy = merge, rollback = revert, both with review and history in the shared change log.
  • Emergency changes still go through Git (a fast-track review), or selfHeal will undo them — agree on this before an incident, and document how to pause sync if needed.
  • The GitOps controller is a dependency: if Argo CD is down, running workloads continue but no deploys or rollbacks happen. Have a break-glass procedure.
  • prune: true deletes whatever is removed from Git — protect namespaces and stateful resources from accidental pruning.

Disaster recovery benefit#

If every cluster’s desired state is in Git and every cloud resource is in Terraform, rebuilding an environment is a matter of applying them — except for data, which is the subject of Module 9. Test this: rebuild a staging environment from scratch periodically and time it.

A worked example#

A plan for a routine change to the orders database:

  # aws_db_instance.orders must be replaced
-/+ resource "aws_db_instance" "orders" {
      ~ identifier = "orders-prod" -> "orders-production" # forces replacement
      …
    }
Plan: 1 to add, 0 to change, 1 to destroy.

A rename that looked cosmetic would have destroyed and recreated the production database. The reviewer catches it because the CI posts the plan in the pull request and a policy rule flags any plan that destroys a resource tagged stateful=true. With prevent_destroy, the plan would have failed outright.

The program is a tiny drift detector and plan checker: it compares desired and actual state and refuses plans that would destroy stateful resources.

Code#

Go
// drift.go — compare desired and actual state, and block plans that destroy stateful resources.
package main

import (
	"fmt"
	"sort"
)

type resource struct {
	kind     string
	attrs    map[string]string
	stateful bool
}

type action struct{ op, id, detail string }

func plan(desired, actual map[string]resource) []action {
	var out []action
	ids := map[string]bool{}
	for id := range desired {
		ids[id] = true
	}
	for id := range actual {
		ids[id] = true
	}
	keys := make([]string, 0, len(ids))
	for id := range ids {
		keys = append(keys, id)
	}
	sort.Strings(keys)
	for _, id := range keys {
		d, inD := desired[id]
		a, inA := actual[id]
		switch {
		case inD && !inA:
			out = append(out, action{"create", id, ""})
		case !inD && inA:
			out = append(out, action{"destroy", id, "not in code (manual creation, or removed from code)"})
		default:
			for k, v := range d.attrs {
				if a.attrs[k] != v {
					op := "update"
					if k == "identifier" || k == "engine" { // attributes that force replacement
						op = "replace"
					}
					out = append(out, action{op, id, fmt.Sprintf("%s: %q → %q", k, a.attrs[k], v)})
				}
			}
			for k, v := range a.attrs {
				if _, ok := d.attrs[k]; !ok {
					out = append(out, action{"drift", id, fmt.Sprintf("%s=%q set by hand, not in code", k, v)})
				}
			}
		}
	}
	return out
}

func main() {
	desired := map[string]resource{
		"db.orders":    {"aws_db_instance", map[string]string{"identifier": "orders-production", "class": "db.r7g.xlarge", "multi_az": "true"}, true},
		"sg.orders":    {"aws_security_group", map[string]string{"ingress": "10.0.0.0/16:5432"}, false},
		"bucket.audit": {"aws_s3_bucket", map[string]string{"versioning": "enabled"}, true},
	}
	actual := map[string]resource{
		"db.orders":     {"aws_db_instance", map[string]string{"identifier": "orders-prod", "class": "db.r7g.xlarge", "multi_az": "true"}, true},
		"sg.orders":     {"aws_security_group", map[string]string{"ingress": "10.0.0.0/16:5432", "ingress_debug": "0.0.0.0/0:5432"}, false},
		"bucket.audit":  {"aws_s3_bucket", map[string]string{"versioning": "enabled"}, true},
		"vm.temp-debug": {"aws_instance", map[string]string{"type": "c7g.4xlarge"}, false},
	}

	blocked := false
	for _, a := range plan(desired, actual) {
		mark := "  "
		res := actual[a.id]
		if (a.op == "replace" || a.op == "destroy") && res.stateful {
			mark = "✗ "
			blocked = true
		}
		if a.op == "drift" {
			mark = "! "
		}
		fmt.Printf("%s%-8s %-14s %s\n", mark, a.op, a.id, a.detail)
	}
	if blocked {
		fmt.Println("\nPLAN BLOCKED: it would destroy or replace a stateful resource. Use a state move or an explicit, approved migration.")
	}
}

The output also shows two kinds of drift worth an alert by themselves: a security group rule opened to the internet “for debugging”, and a forgotten VM — both created by hand.

Remember this#

  • Infrastructure lives in reviewed code; review the plan, not just the diff.
  • Small state, remote locking, applies from CI, pinned versions, policy as code, deletion protection.
  • GitOps: Git is the desired state; agents pull and reconcile; deploy is a merge, rollback is a revert.
  • Agree in advance how emergency changes work with self-heal, and keep a break-glass path.
  • IaC plus GitOps makes environments rebuildable — test it.

Try it#

  1. Run drift.go. Mark vm.temp-debug as stateful. What changes?
  2. Run terraform plan (or tofu plan) on a project you own and look for any “forces replacement” lines.
  3. Write a policy rule (Conftest/Rego or Checkov) that fails a plan destroying anything tagged stateful=true.

Check yourself#

  1. Why review the plan instead of only the code diff?
  2. What does selfHeal: true do, and how does it interact with emergency manual changes?
  3. Why keep Terraform state small?
  4. What part of an environment can IaC and GitOps not rebuild?

Sources#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in