← [Раздел 07](README.md) · [Главная](../README.md)

# Terraform security

## Цель

Понять риски **Infrastructure as Code (IaC)** на примере Terraform: безопасное state, секреты в модулях, сканирование misconfiguration и контроль drift — чтобы `terraform apply` не открывал базу в интернет.

## Предварительно

- [kubernetes-security.md](kubernetes-security.md), [iam-least-privilege.md](iam-least-privilege.md).
- Terraform basics: provider, resource, module, state.

## Время

~30 минут чтения + scan sample .tf with tfsec

---

## IaC security shift-left

Infrastructure changes проходят через **git PR** — идеальное место для policy checks до apply.

```
.tf PR → fmt/validate → IaC scan → plan review → apply (approved)
```

## Terraform state — crown jewels

**State file** содержит plaintext values ресурсов (including sensitive outputs).

| Rule | Implementation |
|------|----------------|
| Remote state | S3 + DynamoDB lock / Terraform Cloud |
| Encrypt at rest | SSE-KMS on bucket |
| No state in git | `.gitignore` terraform.tfstate |
| IAM on bucket | CI role only, no human wide access |
| Versioning | Rollback corrupt state |

Leak state = leak DB passwords from outputs.

## Secrets in Terraform

| ❌ | ✅ |
|----|-----|
| `password = "secret123"` in .tf | `var.db_password` from CI env / TF_VAR_ |
| Secret in `terraform.tfvars` committed | tfvars in gitignore; use Vault data source |
| Output sensitive=false for key | `sensitive = true` + no log in CI |

Use **external secret stores**: AWS Secrets Manager data source, HashiCorp Vault provider.

## Least privilege for CI role

Terraform runner role:

- Scoped to required services/regions
- Separate roles: plan (read) vs apply (write) optional
- No `*` actions on `*` resources

## IaC scanning tools

| Tool | Engine |
|------|--------|
| **tfsec** | Terraform static |
| **Checkov** | Multi-IaC |
| **Trivy** | Terraform + K8s manifests |
| **terraform validate** | Syntax |
| **OPA/conftest** | Custom policies |

CI example (concept):

```bash
terraform fmt -check
terraform validate
tfsec .
checkov -d .
```

Gate: Critical misconfig blocks merge.

## Common misconfigurations

| Misconfig | Scanner rule theme |
|-----------|-------------------|
| S3 bucket public ACL | AWS S3 public access |
| SG `0.0.0.0/0` on 22 | Open SSH |
| RDS publicly accessible | Database exposure |
| CloudTrail disabled | No audit trail |
| Unencrypted EBS/RDS | Data at rest |
| Overly open IAM policy | `iam.*` wildcard |

Map findings to [network segmentation](seti-segmentaciya.md) and [IAM](iam-least-privilege.md) fixes.

## Module supply chain

| Risk | Mitigation |
|------|------------|
| Unknown public module | Pin version, vet source |
| Typosquat module name | Internal registry mirror |
| Module calls external HTTP | Review `data` sources |

Prefer internal golden modules with security defaults.

## Plan review (human)

Automated scan не понимает context.

Reviewer checklist on `terraform plan`:

- [ ] New public ingress intentional?
- [ ] IAM policy diff minimal?
- [ ] Destroy operations expected?
- [ ] New resources tagged (owner, env)?

Require two-person rule for prod apply (optional maturity).

## Drift detection

Manual console change ≠ Terraform code → **drift**.

| Problem | Solution |
|---------|----------|
| Shadow admin opened port | Scheduled `terraform plan` alert non-empty |
| Emergency hotfix | Import or revert + codify |

Tools: Terraform Cloud drift detection, scheduled plan in CI.

## Environments

| Practice | Benefit |
|----------|---------|
| Separate state per env | Blast radius |
| Separate AWS accounts | Strong isolation |
| Same modules, different tfvars | Consistency |
| No prod creds in dev CI | Leak containment |

## Policy as code example intents (OPA)

- Deny `aws_s3_bucket` without `block_public_acls = true`
- Require `encryption` on RDS
- Deny IAM policy with `"Action": "*"`

## Terraform + K8s

Often two repos/layers:

1. Terraform — cluster, VPC, IAM
2. Helm/Kustomize — workloads

Scan both; don't assume secure cluster if manifests deploy `:latest` privileged pod.

## Checklist

- [ ] Remote encrypted state, not in git
- [ ] No secrets in .tf / committed tfvars
- [ ] tfsec/Checkov in PR pipeline
- [ ] CI role least privilege
- [ ] Plan review for prod
- [ ] Drift detection scheduled
- [ ] Module versions pinned

---

## Самопроверка

1. Почему terraform.tfstate опаснее обычного .tf файла?
2. Назовите 3 misconfigurations, которые IaC scanner ловит хорошо.
3. Чем drift отличается от misconfiguration в code?
4. Где хранить `db_password` для Terraform apply?

## Дальше

Раздел 07 завершён. Переходите к [разделу 08 — Runtime и мониторинг](../08-runtime-monitoring/README.md).
