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 создаёт, меняет или удаляет реальные ресурсы, приводя реальность к твоему описанию.
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 ночи».
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" }
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. Ежедневный рабочий цикл
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.
destroya 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 до мёрджа.
7. Quick self-check7. Быстрая самопроверка
Answer in your head, then tap to flip.Ответь про себя, потом нажми, чтобы перевернуть.