Comprehensive Rules for building, validating, and operating immutable, multi-cloud infrastructure using Terraform (HCL) and Ansible (YAML). Includes language conventions, error-handling, drift detection, CI/CD integration, testing, security, and performance guidance.
Your infrastructure configuration shouldn't be a constant battle against manual drift, security misconfigurations, and environment inconsistencies. These Cursor Rules transform your Terraform and Ansible workflows into a bulletproof, immutable infrastructure pipeline that scales across multi-cloud environments.
Every infrastructure team knows the pain:
These aren't just minor inconveniences—they're productivity killers that cost hours of debugging and create production outages.
These Cursor Rules implement enterprise-grade configuration management patterns that eliminate infrastructure drift and enforce consistency across your entire stack. You get automated drift detection, security-first configurations, and seamless multi-cloud operations built into every resource you create.
The rules enforce immutable infrastructure principles where resources are replaced rather than modified, ensuring your production environment always matches your code. Combined with proactive compliance checking and automated remediation, you catch configuration issues before they reach production.
What makes this different: Instead of generic IaC guidelines, these rules provide opinionated, battle-tested patterns specifically designed for complex, multi-environment operations.
Before: Manually copying Terraform configurations between environments, forgetting to update region-specific values, dealing with inconsistent resource naming.
With these rules:
# Automatically enforced module structure
module "vpc_core" {
source = "./modules/networking"
environment = var.environment
project = var.project
# Mandatory tags enforced by rules
tags = local.mandatory_tags
# Provider-agnostic resource naming
vpc_name = "${var.project}-${var.environment}-vpc"
}
Your code automatically follows naming conventions, includes mandatory tags, and works consistently across all environments. The rules ensure every resource is tagged for cost tracking and compliance.
Before: Infrastructure changes happening through the console, discovered days later when applications start failing, requiring manual investigation to identify what changed.
With these rules:
# Automated drift detection in CI
terraform plan -detailed-exitcode
aws configservice describe-compliance-by-config-rule
AWS Config rules automatically detect when someone modifies resources outside Terraform. You get Slack notifications within minutes, and the rules provide automated remediation scripts to restore desired state.
Before: Manually reviewing infrastructure for security issues, secrets accidentally committed to version control, compliance violations discovered during audits.
With these rules:
# Ansible vault integration enforced
vault_encrypted_secrets: !vault |
$ANSIBLE_VAULT;1.1;AES256
# Automatic security scanning
- name: Validate security group rules
assert:
that:
- item.cidr_blocks != ["0.0.0.0/0"]
fail_msg: "Security group allows unrestricted access"
Every secret is automatically encrypted with Ansible Vault, security scanning runs on every commit, and compliance checks are built into your deployment pipeline.
Add the rules to your .cursorrules file:
{
"rules": "immutable-iac-config-management"
}
Configure your workspace with the required tools:
# Install validation tools
brew install tflint tfsec ansible-lint
pip install checkov molecule
# Set up pre-commit hooks
pre-commit install
The rules automatically enforce this directory structure:
infrastructure/
├── modules/
│ ├── networking/
│ ├── compute/
│ └── security/
├── environments/
│ ├── dev/
│ ├── staging/
│ └── prod/
└── ansible/
├── roles/
├── playbooks/
└── inventory/
Set up remote state with automatic locking:
terraform {
backend "s3" {
bucket = "your-terraform-state"
key = "infrastructure/terraform.tfstate"
region = "us-west-2"
dynamodb_table = "terraform-locks"
encrypt = true
}
}
The rules automatically configure AWS Config for drift detection:
resource "aws_config_config_rule" "terraform_managed" {
name = "terraform-managed-resources"
source {
owner = "AWS"
source_identifier = "REQUIRED_TAGS"
}
input_parameters = jsonencode({
tag1Key = "terraform:managed"
tag1Value = "true"
})
}
Teams using these rules report:
You're not just writing Infrastructure as Code—you're building a self-healing, automatically compliant infrastructure platform that scales with your organization. The rules eliminate the manual overhead of configuration management while ensuring your infrastructure remains secure, consistent, and auditable across its entire lifecycle.
You are an expert in Terraform (HCL), Ansible (YAML), AWS Config, Helm, Kubernetes, Bash, and GitHub Actions.
Key Principles
- Treat infrastructure the same as application code (IaC first, everything version-controlled).
- Immutability over mutability: never mutate resources in place—replace.
- Declarative definitions > imperative scripts; keep state deterministic and reproducible.
- Single source of truth: one module/role per responsibility; no duplicated values.
- Automate everything: provisioning, drift detection, security/compliance checks.
- Fail fast: detect errors and drift in CI before reaching production.
- Multi-cloud consistency: abstract provider specifics behind modules/roles.
- Security and least privilege baked in from day-zero.
- Document intent inline; every file must be understandable without tribal knowledge.
- Continuous improvement: measure, monitor, refactor, and upgrade tools regularly.
HCL (Terraform)
- File layout
- root/main.tf → provider, backend, remote state
- root/variables.tf → input variables (description, type, sensible defaults)
- root/outputs.tf → consumable outputs only (prefixed with module name)
- modules/<name>/{main,variables,outputs}.tf → self-contained modules
- locals.tf → computed values; use locals.* rather than repeated expressions.
- Naming
- Resources: <service>_<purpose> (aws_vpc_core, azurerm_rg_shared).
- Variables: snake_case; boolean variables prefixed with "enable_" (e.g., enable_logging).
- Tags/labels: mandatory keys {env, project, owner, cost_center}.
- Style
- Two-space indent, max 100-char line, trailing commas on multi-line blocks.
- Use for_each over count when unique keys exist; prefer dynamic blocks to duplication.
- Always pin provider versions (>= 5.0, < 6.0) and module versions with exact tags.
- State
- Remote backend S3 + DynamoDB lock by default; never commit *.tfstate.
- Use workspaces only for ephemeral POC; prefer separate state files per environment.
- Validation
- Write terraform validation blocks and pre-commit hooks (tflint, tfsec, terraform-fmt).
YAML (Ansible)
- Directory layout (Kubernetes-style):
roles/<role>/tasks/, handlers/, templates/, files/, defaults/, vars/, meta/
- Naming conventions
- Variables: lowercase + underscores; booleans start with "is_" or "enable_".
- Playbook names: <scope>-<purpose>.yml (e.g., webserver-provision.yml).
- Style
- 2-space indent; no tabs; wrap > 120 chars.
- Always include "name:" on every task; make names imperative and descriptive.
- Idempotence
- Use *state: present/absent* over shell cmds; shell/command only when module missing.
- Version pinning
- Collections and roles pinned in requirements.yml with semantic versions.
- Lint & validation
- ansible-lint mandatory; yamllint integrated in CI.
Error Handling and Validation
- Detect drift
- Terraform: terraform plan in cron/CI + infracost to compare cost drift.
- AWS Config & Azure Policy for cloud-native drift alerts; CloudWatch/EventBridge notifications.
- Early failure
- add "-lock-timeout=60s" and retry-logic wrapper for terraform apply.
- Ansible: block/rescue/always with assert & set_fact for critical vars.
- Compliance gates
- tfsec, checkov, terrascan executed on PR.
- Ansible: openscap and complianceascode roles executed in CI.
Framework-Specific Rules
Terraform
- Separate layers: networking → shared services → application.
- Use data sources instead of hard-coding IDs; never reference random IDs.
- Outputs are interface; never export secrets—pass via secret manager instead.
- Use lifecycle { prevent_destroy = true } for critical resources.
Ansible
- Prefer *import_* over *include_* at playbook parse-time for errors early.
- Use inventory plugins (aws_ec2, azure_rm) instead of static files.
- Encrypt sensitive vars with Ansible Vault; decrypt via CI secrets.
Helm & Kubernetes
- Keep charts in /helm chart/ with Chart.lock pinned.
- Values schema.json for validation; use helm-lint in CI.
- Release names: <env>-<service>; namespace per workload; enable CRDs via separate sync.
AWS Config
- Rules baseline enforced via terraform aws_config_config_rule; remediation via SSM automation docs.
Additional Sections
Testing
- Terraform: Terratest in Go with parallel=true; use mock endpoints for cloud APIs.
- Ansible: Molecule with Docker driver; converge + verify stages must succeed.
Performance & Scalability
- Split large terraform applies (<500 resources) into smaller modules to reduce plan time.
- Enable Ansible pipelining & ssh_control_path for faster runs.
Security
- Use SOPS-encrypted .tfvars/vars files; keys managed in KMS.
- No plain text secrets; integrate with AWS Secrets Manager, Azure Key Vault, HashiCorp Vault.
- Activate terraform exec environment variable TF_CLI_CONFIG_FILE to load credentials from isolated config.
CI/CD Integration
- PR → pre-commit (fmt, validate, lint) → plan (no-apply) → policy as code (OPA) → cost estimation > comment.
- Main branch merge: terraform apply with auto-approve in non-prod; manual confirm in prod.
- Ansible: dry-run (-C) in CI; prod runs gated by protected environment rules.
Documentation
- Every module/role must have README.md with inputs/outputs/examples generated by terraform-docs or ansible-lint-rules.
Common Pitfalls & Remedies
- Hard-coding provider regions → Always expose as variable with default.
- Direct interpolation of sensitive outputs → Use data/lookup.
- Drifts due to manual console edits → Enable IAM deny tags ("terraform:managed") and enforce RBAC.