Terraform Advanced — Cost Tagging & Drift Detection

1 minute read

Track cloud spending and detect when infrastructure drifts from code.


Enforce Tags via default_tags

provider "aws" {
  region = "us-east-1"

  default_tags {
    tags = {
      Environment = var.environment
      Team        = var.team
      ManagedBy   = "terraform"
      CostCenter  = var.cost_center
      Project     = var.project
    }
  }
}

Every resource in this provider automatically gets these tags.


Tag Validation

variable "environment" {
  type = string
  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "Environment must be dev, staging, or prod"
  }
}

variable "cost_center" {
  type = string
  validation {
    condition     = can(regex("^CC-\\d{4}$", var.cost_center))
    error_message = "Cost center must match CC-XXXX pattern"
  }
}

Drift Detection

Scheduled Plan in CI

# .github/workflows/drift.yml
name: Drift Detection
on:
  schedule:
    - cron: '0 8 * * 1-5'  # Weekdays at 8 AM

jobs:
  drift:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: hashicorp/setup-terraform@v3
      - run: terraform init
      - run: |
          terraform plan -detailed-exitcode
          # Exit code 2 = changes detected (drift!)
        continue-on-error: true
      - name: Alert on drift
        if: steps.plan.outcome == 'failure'
        run: |
          # Send Slack/PagerDuty notification

AWS Config Rule

resource "aws_config_config_rule" "required_tags" {
  name = "required-tags"
  source {
    owner             = "AWS"
    source_identifier = "REQUIRED_TAGS"
  }
  input_parameters = jsonencode({
    tag1Key = "Environment"
    tag2Key = "Team"
    tag3Key = "ManagedBy"
  })
}

What’s Next?

The null_resource escape hatch.

← Zero-Downtime Deployments null_resource Escape Hatch →

Updated: