Drift Detection: Identifying differences between the code state and the actual infrastructure state.
Peer Reviews: A human approval step.
Staging Rollouts: Testing in non-production environments first.
Rollback Procedures: How to revert changes when things go wrong.
Audit Trails: Logging who did what and when.
The user is asking for an implementation. This implies code, configuration, or a very concrete architectural design, not just a theoretical discussion. Since I am a text-based AI, I cannot set up a live server, but I can provide the blueprints, code snippets (e.g., Terraform, GitHub Actions/CircleCI, OPA/Checkov), and the directory structure needed to build this.
Technology Stack Choices:
To make the implementation concrete, I need to choose standard tools.
IaC Tool: Terraform (Industry standard).
CI/CD Platform: GitHub Actions (Widely accessible) or GitLab CI. Let's go with GitHub Actions for the examples.
Policy as Code: Open Policy Agent (OPA) with Rego or Checkov. Let's use OPA for flexibility or Checkov for ease of use. Let's go with Checkov as it's easier to demonstrate in a single pipeline, but OPA is more powerful. Let's stick to a general "Policy Check" step which could use either. Let's use OPA/Conftest for a "custom" feel or just mention Checkov/Sentinel. Actually, tflint and checkov are very common. Let's use Checkov for the example.
Drift Detection: Terraform native capabilities within the CI pipeline (scheduled jobs).
Module Registry: Git-based versioning (tags) or a private registry (Terraform Cloud/Artifactory). I will demonstrate Git tags for simplicity.
Safety & Compliance Note:
This is a request for operational infrastructure code. It is helpful and harmless. No specific restrictions apply other than standard quality.
Self-Correction/Optimization during drafting:
I initially thought about OPA, but writing Rego policies might be too verbose for a general implementation guide. I will mention OPA but use tflint and tfsec or checkov in the YAML examples as they are more plug-and-play.
For the "Audit Trail", simply saying "check the logs" is weak. I should mention generating an artifact of the plan output and storing it, or using a tool like Spacelift/Scalr if they want enterprise features, but stick to the "implementation" requested which implies doing it yourself or via code. I will suggest storing plan outputs as artifacts.
Final Plan:
Repo Layout: Mono-repo vs Multi-repo. Mono-repo with distinct environments is easier to demo.
Module Strategy: Semantic versioning.
Pipeline: The heavy lifter.
Step 1: Validation & Security (Checkov).
Step 2: Plan (Staging).
Step 3: Approval (Staging).
Step 4: Apply (Staging).
Step 5: Plan (Prod).
Step 6: Approval (Prod).
Step 7: Apply (Prod).
Drift: Cron job.
Rollback: Revert PR.
Audit: S3 backend with versioning + Lock table + CI logs.
Let's write this out.
This implementation guide outlines a production-grade Infrastructure as Code (IaC) workflow using Terraform and GitHub Actions (concepts apply to GitLab CI/Jenkins as well). It focuses on shifting left with policy checks while maintaining safety through staged rollouts and auditability.
Module Versioning Strategy:
In live/staging/main.tf, strictly reference modules via Git tags or registry versions. Never reference the main branch directly in production.
We use Open Policy Agent (OPA) with Conftest or Checkov to validate the Terraform plan JSON before deployment. This prevents non-compliant resources (e.g., unencrypted S3 buckets, public S3 ACLs).
Workflow Step (GitHub Actions):
yaml
# Inside .github/workflows/infrastructure.yaml
jobs:
validate-policy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: hashicorp/setup-terraform@v2
- name: Terraform Init
run: terraform init -backend=false
# Generate a plan file
- name: Terraform Plan
run: terraform plan -out=tfplan.binary
# Convert plan to JSON for OPA/Conftest
- name: Convert Plan to JSON
run: terraform show -json tfplan.binary > tfplan.json
# Run Policy Checks
- name: Check Policies (Conftest)
uses: instrumenta/conftest-action@master
with:
files: tfplan.json
policy: policies/
Example Policy (policies/enforce_tags.rego):
rego
package main
deny[msg] {
input.resource_changes[_].type == "aws_instance"
not input.resource_changes[_].change.after.tags["Environment"]
msg := "EC2 instances must have an 'Environment' tag"
}
3. Peer Reviews & Branch Protection
This is configured in the Git hosting platform settings (e.g., GitHub Branch Protection Rules).
Configuration:
Require Pull Request: No direct commits to main or live/production.
Required Status Checks: The validate-policy job from step 2 must pass before merging is allowed.
Code Owners: Create a CODEOWNERS file to require approval from specific teams (e.g., the @security-team must approve changes to policies/).
Note: The environment: production setting in GitHub Actions allows you to set up Environment Protection Rules, requiring a human click to approve the deployment.
5. Drift Detection
Drift occurs when manual changes are made in the console (AWS/Azure) outside of Terraform.
Implementation: Create a scheduled workflow (e.g., daily at 6 AM UTC).
There are two main strategies depending on the severity.
Strategy A: terraform apply (Safe & Standard)
If a new feature breaks staging, you simply revert the Git commit and re-run the pipeline. Terraform will calculate the diff to return to the previous state and apply it.
git revert <commit-sha>
git push origin main
Pipeline triggers -> Plan -> Apply (Restoring old state).
Strategy B: State Recovery (Disaster Recovery)
If the state file is corrupted or a destructive change occurred that Terraform cannot easily revert:
Identify State File: Locate the state file in the backend (e.g., S3).
Restore Versioning: Enable versioning on the S3 bucket storing the .tfstate.
Rollback:
Disable Terraform backend temporarily or copy an older version of the state file from S3 version history.
Run terraform state push older_state.tfstate to force the state back in time.
Run terraform apply to sync the real infrastructure with the rolled-back state.
7. Audit Trails
Git Log: Every change is tied to a Pull Request, Commit SHA, and Author.
Terraform State: Each terraform.tfstate file contains a lineage and serial number, tracking the history of modifications.
Locking: Ensure your backend (S3 + DynamoDB) has locking enabled to prevent concurrent runs which break audit trails.
Cloud Provider Logs: Ensure CloudTrail (AWS) / Activity Logs (GCP) are enabled. If an audit is required, you cross-reference the Git commit timestamp with the CloudTrail event timestamp.
Visualizing the Audit:
Who:git log --author / GitHub Actor.
What:git diff / Terraform Plan output stored in CI artifacts.