Infrastructure as Code (Terraform basics)
Define and provision cloud infrastructure using declarative configuration files that are version-controlled and peer-reviewed.
Description
Infrastructure as Code (IaC) is the practice of defining cloud infrastructure (servers, databases, networks, DNS, IAM policies) using declarative configuration files rather than manual console operations. Terraform, by HashiCorp, is the most widely adopted IaC tool, using HCL (HashiCorp Configuration Language) to define resources across multiple cloud providers. This approach makes infrastructure reproducible, version-controlled, peer-reviewed, and auditable.
Terraform works by comparing the desired state (defined in .tf files) with the current state (stored in a state file) and computing a plan of changes needed to reconcile the difference. The plan is reviewed before applying, preventing unexpected changes. State files should be stored remotely (S3 + DynamoDB for locking, Terraform Cloud, or similar) and never committed to version control, as they may contain sensitive values.
Best practices include organizing code into modules for reusability, using workspaces or directory-based environments for dev/staging/prod separation, pinning provider and module versions, using data sources to reference existing infrastructure, implementing policy-as-code with tools like Sentinel or OPA, and running terraform plan in CI with the output saved for review. Variables should be typed and validated, secrets should come from a secret manager (not tfvars files), and outputs should expose values needed by other systems. Terraform Cloud or Atlantis can automate plan-on-PR and apply-on-merge workflows.
Prompt Snippet
Define Terraform configuration for the production environment: VPC with public/private subnets across 3 AZs, ECS Fargate cluster with an ALB, RDS PostgreSQL 16 Multi-AZ instance in private subnets, ElastiCache Redis cluster, and S3 bucket for assets with CloudFront distribution. Organize into modules (networking, compute, database, cdn). Store state in S3 with DynamoDB locking and enable state encryption. Pin the AWS provider to ~>5.0. Use terraform-docs for auto-generated module documentation, tflint for linting, and checkov for security scanning in CI. Run terraform plan on PRs via Atlantis with required approval before terraform apply on merge to main.
Tags
Related Terms
DNS Configuration
Configure DNS records to map domain names to server IP addresses, services, and other infrastructure endpoints.
Secrets in CI/CD
Securely store, access, and rotate sensitive credentials used in CI/CD pipelines without exposing them in code or logs.
Container Orchestration (Kubernetes basics)
Automate deployment, scaling, and management of containerized applications using Kubernetes.
CI/CD Pipeline Design
Automate building, testing, and deploying code through a structured pipeline triggered by version control events.