Terraform и Infrastructure as Code
(Section: Technology and Infrastructure)
Brief Summary
Terraform is the basic IaC tool for reproducible and verifiable creation of iGaming cloud infrastructure: VPC/subnets, Balancers, databases/clusters, queues/buses, KMS/Secrets, Kubernetes clusters, CDN and monitoring. Success rests on a modular architecture, strict state and lock policies, GitOps approach to releases, Policy-as-Code, automated testing and transparent FinOps.
1) IaC principles for iGaming
Declarative: infrastructure described by code; there are no manual steps.
Idempotency: repeated 'apply' gives the same result.
Separation of environments: 'dev/stage/prod' from a single code with parameters.
Module composition: a single catalog of modules for VPC, DB, queues, K8s, monitoring.
Default security: private subnets, mTLS, minimum IAM rights.
Observability and cost: metrics/alerts/budgets are also under Terraform.
2) Repository structure
Monorepo variant (example):
iac/
modules/
vpc/
mysql/
kafka/
eks_aks_gke/
redis/
monitoring/
envs/
prod/
eu-west/
main. tf variables. tf backend. tf stage/
eu-west/
...
dev/
...
policies/
opa/
sentinel/
pipelines/
ci_cd/
The alternative is a modular repo (a separate repository for each module) + consumers.
3) Basic modularity (HCL example)
VPC module (modules/vpc/main. tf):hcl variable "name" {}
variable "cidr" {}
variable "az_count" { default = 3 }
cloud provider resources (summarized)
resource "cloud_vpc" "this" { name = var. name cidr = var. cidr }
resource "cloud_subnet" "private" {
count = var. az_count vpc_id = cloud_vpc. this. id type = "private"
}
output "vpc_id" { value = cloud_vpc. this. id }
output "private_subnets" { value = cloud_subnet. private[].id }
Module consumption (envs/prod/eu-west/main. tf):
hcl module "vpc" {
source = "../../modules/vpc"
name = "prod-eu-west"
cidr = "10. 20. 0. 0/16"
}
module "mysql" {
source = "../../modules/mysql"
name = "payments"
vpc_id = module. vpc. vpc_id subnets = module. vpc. private_subnets pitr = true size = "r6g. large"
kms_key = module. kms. key_id
}
4) State management and locks
Remote backend (for example, object storage) + locks (DynamoDB/Blob-lock) - prevent 'apply' races.
Backend versioning and state encryption (KMS).
Access rules: only CI/CD and "infra owners" have 'apply' rights; developers - 'plan'.
- Workspaces are convenient for similar environments (replication),
- Separate directories - for clearly isolated configurations and different topologies.
hcl terraform {
backend "s3" {
bucket = "iac-state-prod"
key = "eu-west/terraform. tfstate"
region = "eu-west-1"
dynamodb_table = "iac-state-locks"
encrypt = true
}
}
5) Variables, secrets and sensitive data
variables. tf + .tfvars for environments; sensitive = true for private values.
Secrets are not stored in Git. Use the Secret Manager/KMS through data-source or provider.
Default encryption: for volumes/backups/snapshots/databases.
Rotation: keys and passwords are automatically rotated.
hcl variable "db_password" {
type = string sensitive = true
}
data "external_secret" "db_password" {
conceptual secret source name = "prod/payments/db_password"
}
6) GitOps and CI/CD for Terraform
PR flow: 'terraform fmt' → 'init' → 'validate' → 'tflint' → 'plan' with output to PR → manual approve → 'apply' from CI.
Environment promotion: changes first in 'stage', then tag/merge in 'prod'.
Logs and artifacts: saving plan and diffa, artifact-report.
yaml steps:
- run: terraform fmt -check
- run: terraform init -upgrade
- run: terraform validate
- run: tflint --enable-rule=terraform_standard_module_structure
- run: terraform plan -var-file=envs/stage/eu-west/vars. tfvars -out tfplan
- run: terraform show -no-color tfplan > plan. txt after April
- run: terraform apply tfplan
7) Policy-as-Code (OPA/Sentinel)
Purpose: automatically reject unsafe/expensive changes.
Examples of policies:- Resource encryption is required.
- Public IP - only through the exception list.
- Limiting the size of instances/clusters by environment.
- Required tags: 'env', 'owner', 'cost _ center'.
rego deny[msg] {
input. resource. type == "db_instance"
not input. resource. encrypted msg:= "DB must be encrypted at rest"
}
8) IaC testing
terraform validate-Basic syntax check.
tflint - style/antipatterns/provider-specificity.
Infracost - preliminary cost estimate in PR.
Terratest - integration tests (Go): lift/check/demolish the stand.
Kitchen-Terraform - unit tests with resource invariants.
Drift-detection: periodic 'plan' in read-only and out-of-sync alert.
9) Typical modules for the iGaming platform
Network
VPC/VNets/VPC-Peering, private/public subnets, routing, NAT/Firewall, Security Groups/NSG.
DNS/Failover: Route-политики, health-checks, latency-based routing.
Data
MySQL/PostgreSQL: Multi-AZ, PITR, `auto_minor_version_upgrade`.
Redis/Memcached: Multi-AZ, snapshot/TTL policies.
Data Lake/Lakehouse: buckets, policies, tables (catalog/metastor).
ClickHouse/OLAP clusters: shardiness/replication, disk policies.
Buses/Queues
Kafka/Pulsar/managed variants, ACL, retention, registry schemes.
K8s
EKS/AKS/GKE с NodeGroups, taints/tolerations, IRSA/Workload Identity, Ingress/Service Mesh, autoscaling.
Integration of External Secrets, Prometheus/Grafana, Loki/ELK, cert-manager.
Edge/CDN
CDN distribution, caching rules, WAF, bot mitigation.
10) Variables/Outputs/locals - practice
locals for calculated values (masks, names).
outputs as module API: minimum required.
Resource naming '<env> - <region> - <domain> - <component>'.
Тэги: `env`, `owner`, `cost_center`, `criticality`, `pii`.
hcl locals {
name_prefix = "${var. env}-${var. region}-${var. service}"
}
resource "cloud_lb" "api" { name = "${locals. name_prefix}-lb" }
11) Multi-cloud and regions
Abstraction through the same modules, different providers: 'aws', 'azurerm', 'google'.
Provider alias for cross-regional resources (DR/replication).
Service differences are closed by conditions and phicheflags in modules.
Data are localized: individual buckets/DB by region (EU/TR/LATAM).
hcl provider "aws" { region = "eu-west-1" alias = "eu" }
provider "aws" { region = "sa-east-1" alias = "latam" }
12) Observability and alerts as code
Dashboards, alert rules (p95/p99, error-rate, CPU/IO), SLO monitors.
Access/audit logs (WORM), cost metrics (by tag/namespace).
Incidents: chat notifications, runbooks URLs in resource annotations.
13) FinOps: Value Under Control
Infracost in PR + budget alerts.
Environment quotas: limiting instance/warehouse classes.
Auto-hygiene: TTL for dev resources, bucket/log retention policies.
Spot/Preemptible for non-critical tasks, reservation for Prod.
14) Migration/Change Processes
'terraform import'for legal resources (immediately after -' plan '/' apply ').
'moved '/' removed'blocks when refactoring to avoid destruction.
Zero-downtime changes: double rolling (blue-green) for critical contours (DB/balancers).
Step-by-step PR: new resource group first, then traffic, then dismantling.
15) Safety and compliance
Least privilege: modules create only the necessary rights, do not use. "
KMS everywhere: encryption of volumes/backups/secrets/states.
Terraform/IaC scan in CI (SAST for IaC).
Secrets Outside Git: Secret Managers Only; rotation and access audit.
PII zones: access tags/policies, interregional export ban.
16) Sample templates
Relational database with PITR (idea):hcl module "db" {
source = "../../modules/mysql"
name = "wallet"
multi_az = true storage_gb = 500 pitr = true backup_retention_days = 14 deletion_protection = true
}
Monitoring and SLO alert:
hcl module "slo_latency" {
source = "../../modules/monitoring/slo"
name = "api-latency-p95"
target_ms = 250 window = "30m"
alert_channels = ["chatops#incidents"]
}
WAF/CDN distribution:
hcl module "cdn" {
source = "../../modules/cdn"
domain = "example. com"
waf_enabled = true cache_ttl = 600
}
17) Terraform/IaC Implementation Checklist
1. Select the repository structure (module monorepos + environment directories).
2. Configure remote state with locks and encryption (KMS).
3. Enter GitOps-pipeline: fmt/validate/tflint/plan → review → apply.
4. Create a module library (VPC, K8s, DB, queues, monitoring, CDN, secrets).
5. Enable Policy-as-Code (OPA/Sentinel) and IaC scans in the CI.
6. Organize secrets through the manager, keys - KMS, rotations.
7. Add tests: Terratest for critical modules, Infracost in PR.
8. Define SLO/alerts and "monitoring as code."
9. Set up quotas/budgets and TTL for non-critical resources.
10. Plan migrations in stages (blue-green/two-rail).
18) Antipatterns
Manual "snowflakes" of resources outside Terraform → drift and accidents when 'apply'.
Storing a state locally/without locks → racing and loss of consistency.
Secrets in Git/in '.tfvars' without encryption.
"God-module" for hundreds of resources → the inability to test/reuse.
Direct 'apply' from laptop to food without PR and plan review.
Ignoring Policy-as-Code/scans → leaks, public IP/buckets.
Lack of Infracost/budgets → unpredictable cost.
Summary
Terraform/IaC gives the iGaming platform reproducibility, speed, and controlled safety/cost. Modular design, strict state and GitOps, security policies, autotests and FinOps turn infrastructure into a reliable "pipeline" - fast releases without downtime, predictable p99 and readiness for peak tournaments and regulatory requirements.