Terraform & Infrastructure as CodeTerraform и Infrastructure as Code

Describe your cloud infrastructure in code; Terraform makes the real world match it. Declarative, idempotent, multi-cloud. Опиши свою облачную инфраструктуру кодом; Terraform приводит реальный мир к этому описанию. Декларативно, идемпотентно, мультиоблачно.
🏗️ Terraform ☁️ AWS · Azure · GCPAWS · Azure · GCP ⚙️ Cloud & DataOpsCloud и DataOps

1. What is Terraform?1. Что такое Terraform?

Terraform (by HashiCorp) is an Infrastructure as Code (IaC) tool. Instead of clicking around a cloud console to create servers, databases and networks, you describe the infrastructure you want in text files, and Terraform creates, changes, or deletes real resources to make reality match your description.

Terraform (от HashiCorp) — это инструмент Infrastructure as Code (IaC). Вместо кликанья по облачной консоли, чтобы создавать серверы, базы и сети, ты описываешь нужную инфраструктуру в текстовых файлах, а Terraform создаёт, меняет или удаляет реальные ресурсы, приводя реальность к твоему описанию.

AnalogyАналогия It's like a blueprint + a robot builder. You write the blueprint ("two servers, one database, this network"). The robot compares the blueprint with what's already built and does only the difference — adds what's missing, fixes what changed, removes what you deleted. Это как чертёж + робот-строитель. Ты пишешь чертёж («два сервера, одна база, такая сеть»). Робот сравнивает чертёж с тем, что уже построено, и делает только разницу — добавляет недостающее, чинит изменившееся, убирает удалённое.
One lineОдной строкой Terraform = declarative, version-controlled infrastructure: you say what you want, it figures out how to get there and tracks the diff. Terraform = декларативная инфраструктура под версионным контролем: ты говоришь что хочешь, он решает как к этому прийти и отслеживает разницу.

2. What is "Infrastructure as Code"?2. Что такое «Infrastructure as Code»?

IaC means managing infrastructure with files in version control instead of manual clicks. That unlocks the same superpowers we already use for application code:

IaC — это управление инфраструктурой через файлы в системе контроля версий, а не ручными кликами. Это даёт те же суперсилы, что мы уже используем для кода приложений:

  • Reviewable. Infra changes go through pull requests and diffs, like code.
  • Reproducible. Spin up an identical dev/staging/prod from the same files.
  • Versioned. Git history of every infra change; roll back if needed.
  • Auditable. No mystery "who created this server in the console at 2am".
  • Можно ревьюить. Изменения инфры идут через pull request и diff, как код.
  • Воспроизводимо. Поднять идентичные dev/staging/prod из тех же файлов.
  • Версионируется. Git-история каждого изменения инфры; можно откатиться.
  • Аудируется. Никаких загадок «кто создал этот сервер в консоли в 2 ночи».
Declarative, not imperativeДекларативно, не императивно You describe the desired end state, not a script of steps. Terraform computes the steps. Run it twice with no changes → it does nothing (idempotent). Ты описываешь желаемое конечное состояние, а не скрипт шагов. Terraform сам вычисляет шаги. Запусти дважды без изменений → ничего не сделает (идемпотентно).

3. Core concepts3. Ключевые понятия

① Providers① Providers (провайдеры)

Plugins that teach Terraform how to talk to a platform: aws, azurerm, google, and hundreds more. Same Terraform, different provider per cloud.

Плагины, которые учат Terraform общаться с платформой: aws, azurerm, google и сотни других. Тот же Terraform, разный провайдер под каждое облако.

② Resources② Resources (ресурсы)

The actual things you manage: a VM, a bucket, a database. Declared as resource "type" "name" { ... }.

Конкретные вещи, которыми ты управляешь: ВМ, бакет, база. Объявляются как resource "type" "name" { ... }.

③ State③ State (состояние)

A file (terraform.tfstate) that records what Terraform has already created, so it can compute the diff between your code and reality. In teams it lives in remote state (e.g. an S3 bucket) with locking so two people don't apply at once.

Файл (terraform.tfstate), записывающий, что Terraform уже создал, чтобы вычислять разницу между твоим кодом и реальностью. В командах хранится в remote state (например в бакете S3) с блокировкой, чтобы двое не делали apply одновременно.

④ Plan & Apply④ Plan и Apply

terraform plan shows the diff (what will be added/changed/destroyed) without touching anything. terraform apply executes it. destroy tears it down.

terraform plan показывает разницу (что будет добавлено/изменено/удалено), ничего не трогая. terraform apply её применяет. destroy всё сносит.

⑤ Variables, outputs & modules⑤ Переменные, выходы и модули

Variables parameterize configs; outputs expose values (like a created DB's address); modules are reusable bundles of resources you call with different inputs — the DRY of infra.

Variables параметризуют конфиги; outputs отдают значения (например адрес созданной БД); modules — переиспользуемые наборы ресурсов, вызываемые с разными входами — DRY для инфры.

4. A minimal example4. Минимальный пример

A storage bucket on AWS, then the exact same idea on Azure — only the provider and resource names change. Written in HashiCorp's language, HCL.

Бакет хранилища на AWS, затем та же идея на Azure — меняются только провайдер и имена ресурсов. Написано на языке HashiCorp — HCL.

# --- AWS ---
resource "aws_s3_bucket" "data" {
  bucket = "better-de-data-lake"
  tags   = { Project = "better_de" }
}

# --- Azure (same concept, different provider) ---
resource "azurerm_storage_account" "data" {
  name                     = "betterdedata"
  resource_group_name      = "my-rg"
  location                 = "westeurope"
  account_tier             = "Standard"
  account_replication_type = "LRS"
}
The diff loopЦикл разницы Change account_tier to "Premium", run plan → Terraform reads the state, sees one attribute differs, and proposes to update just that. Nothing else is touched. Поменяй account_tier на "Premium", запусти plan → Terraform читает state, видит, что отличается один атрибут, и предлагает обновить только его. Остальное не трогается.

5. The everyday workflow5. Ежедневный рабочий цикл

write .tf files (desired state, in git) │ ▼ terraform init ◀── download providers, configure backend/state │ ▼ terraform plan ◀── diff: desired state vs state file vs real cloud │ shows +create / ~update / -destroy ▼ terraform apply ◀── execute the diff, then update the state file │ ▼ (later) terraform destroy ◀── tear everything down cleanly
Why plan-before-apply mattersПочему plan перед apply важен The plan is a dry-run preview you can review (and gate in CI) before any real change. "Will this destroy my prod DB?" — the plan tells you before you find out the hard way. Plan — это сухой прогон-превью, который можно отревьюить (и поставить гейтом в CI) до любых реальных изменений. «А это не снесёт мою прод-базу?» — plan скажет до того, как узнаешь на практике.

6. Why a data engineer cares6. Почему это важно дата-инженеру

  • You own infra now. Modern DE provisions its own warehouses, buckets, clusters, IAM roles, and orchestrator infra — often via Terraform.
  • Reproducible environments. Stand up an identical staging data platform to test a pipeline change safely.
  • Runs the platform that runs your pipelines. Terraform can provision the Kubernetes cluster that Flyte/Airflow then runs on.
  • Cost & cleanup. destroy a whole experimental environment in one command — no orphaned resources quietly billing you.
  • Collaboration. Infra changes get reviewed like code, with a visible plan diff before merge.
  • Теперь инфра на тебе. Современный DE сам поднимает свои warehouse, бакеты, кластеры, IAM-роли и инфру оркестратора — часто через Terraform.
  • Воспроизводимые окружения. Поднять идентичный staging дата-платформы, чтобы безопасно протестировать изменение пайплайна.
  • Поднимает платформу под твои пайплайны. Terraform может развернуть кластер Kubernetes, на котором затем работает Flyte/Airflow.
  • Стоимость и уборка. destroy целого экспериментального окружения одной командой — никаких забытых ресурсов, тихо жгущих бюджет.
  • Совместная работа. Изменения инфры ревьюятся как код, с видимым plan-diff до мёрджа.
Terraform vs the restTerraform vs остальные Terraform = cloud-agnostic, declarative provisioning (create the infra). Ansible/Chef = configuration management (set up software on existing machines). CloudFormation = AWS-only Terraform. Pulumi = same idea but infra in real languages (Python/TS). Terraform's edge: multi-cloud + huge provider ecosystem. Terraform = провижининг без привязки к облаку, декларативно (создать инфру). Ansible/Chef = управление конфигурацией (настроить софт на существующих машинах). CloudFormation = Terraform только для AWS. Pulumi = та же идея, но инфра на настоящих языках (Python/TS). Преимущество Terraform: мультиоблачность + огромная экосистема провайдеров.

7. Quick self-check7. Быстрая самопроверка

Answer in your head, then tap to flip.Ответь про себя, потом нажми, чтобы перевернуть.

What is Terraform in one line?Что такое Terraform одной строкой?
tapнажми
A declarative Infrastructure-as-Code tool: describe desired infra in HCL, and it creates/changes/destroys real cloud resources to match.Декларативный инструмент Infrastructure-as-Code: описываешь желаемую инфру на HCL, а он создаёт/меняет/удаляет реальные облачные ресурсы под неё.
What is the state file for?Зачем нужен state-файл?
tapнажми
It records what Terraform already created, so it can compute the diff between your code and reality. In teams: remote state + locking.Он записывает, что Terraform уже создал, чтобы вычислять разницу между кодом и реальностью. В командах: remote state + блокировка.
plan vs apply?plan vs apply?
tapнажми
plan = dry-run preview of the diff, touches nothing. apply = actually execute that diff and update state.plan = сухой прогон-превью разницы, ничего не трогает. apply = реально применить эту разницу и обновить state.
Why "declarative" + "idempotent"?Почему «декларативно» + «идемпотентно»?
tapнажми
You describe the end state, not steps. Running apply when nothing changed does nothing — the result depends only on the desired state, not how many times you run it.Описываешь конечное состояние, а не шаги. apply при отсутствии изменений ничего не делает — результат зависит только от желаемого состояния, а не от числа запусков.
How does one config target AWS and Azure?Как один конфиг работает с AWS и Azure?
tapнажми
Via providers. Same Terraform engine + HCL; you swap the provider (aws / azurerm / google) and use that cloud's resource types.Через providers. Тот же движок Terraform + HCL; меняешь провайдер (aws / azurerm / google) и используешь типы ресурсов этого облака.
Terraform vs Ansible?Terraform vs Ansible?
tapнажми
Terraform provisions infra (create the servers/DBs/network). Ansible configures software on machines that already exist. Often used together.Terraform создаёт инфру (серверы/БД/сеть). Ansible настраивает софт на уже существующих машинах. Часто используются вместе.