DevOps · Pleno

Infraestrutura como código: Terraform e o fim do clicar no console

Houve um tempo em que montar infraestrutura significava abrir o console da nuvem e clicar: criar uma máquina aqui, um banco ali, ajustar uma regra de rede acolá. Funciona para uma coisa só. Mas quando você precisa recriar tudo idêntico em outra região, ou descobrir quem mudou o quê três meses atrás, o clique vira pesadelo. Infraestrutura como código (IaC) resolve isso tratando servidores, redes e bancos como código versionado.

O que é infraestrutura como código

IaC é descrever sua infraestrutura em arquivos de texto, versionados no Git como qualquer outro código. Em vez de clicar para criar um servidor, você escreve a definição dele e uma ferramenta a aplica. A infraestrutura passa a ser revisável, reproduzível e rastreável.

Declarativo vs imperativo

Essa distinção cai bastante em entrevista. Na abordagem imperativa, você descreve os passos ("crie esta VM, depois instale isto, depois abra esta porta"). Na declarativa, você descreve o resultado desejado ("quero 3 servidores com esta configuração") e a ferramenta descobre como chegar lá. Terraform é declarativo.

AbordagemVocê descreveExemplo
ImperativoO passo a passoScripts bash, Ansible (em parte)
DeclarativoO estado final desejadoTerraform, CloudFormation

O state file

O Terraform mantém um state file: um registro do que ele já criou no mundo real. É assim que ele compara o que você declarou com o que existe e decide o que mudar. Esse arquivo é crítico — costuma ser guardado em um local remoto e compartilhado (ex. um bucket) para que o time trabalhe sobre a mesma verdade, e protegido porque pode conter dados sensíveis.

O ciclo plan / apply

O fluxo de trabalho do Terraform é desenhado para evitar surpresas. Primeiro você roda plan, que mostra exatamente o que vai mudar, sem mexer em nada. Você revisa, e só então roda apply.

There was a time when building infrastructure meant opening the cloud console and clicking: create a machine here, a database there, tweak a network rule somewhere else. That works for one thing. But when you need to recreate everything identically in another region, or find out who changed what three months ago, clicking becomes a nightmare. Infrastructure as code (IaC) solves this by treating servers, networks and databases as versioned code.

What is infrastructure as code

IaC means describing your infrastructure in text files, versioned in Git like any other code. Instead of clicking to create a server, you write its definition and a tool applies it. The infrastructure becomes reviewable, reproducible and traceable.

Declarative vs imperative

This distinction comes up a lot in interviews. In the imperative approach, you describe the steps ("create this VM, then install this, then open this port"). In the declarative approach, you describe the desired outcome ("I want 3 servers with this configuration") and the tool figures out how to get there. Terraform is declarative.

ApproachYou describeExample
ImperativeThe step-by-stepBash scripts, Ansible (partly)
DeclarativeThe desired end stateTerraform, CloudFormation

The state file

Terraform keeps a state file: a record of what it has already created in the real world. That is how it compares what you declared with what exists and decides what to change. This file is critical — it is usually stored in a remote, shared location (e.g. a bucket) so the team works from the same source of truth, and protected because it may contain sensitive data.

The plan / apply cycle

Terraform's workflow is designed to avoid surprises. First you run plan, which shows exactly what will change without touching anything. You review it, and only then run apply.

terraform plan    # mostra: +2 para criar, ~1 alterar, -0 destruir
terraform apply   # aplica as mudanças após você confirmar
O plan é o seu cinto de segurança. Ele transforma "vamos torcer para dar certo" em "eu vi exatamente o que vai acontecer antes de acontecer". Nunca aplique em produção sem ler o plan.

Idempotência

Uma propriedade central da IaC declarativa é a idempotência: aplicar a mesma configuração várias vezes leva sempre ao mesmo estado. Se a infraestrutura já está como você declarou, o apply não faz nada. Isso é o oposto de um script que, rodado duas vezes, cria recursos duplicados.

Exemplo em HCL

Terraform usa a linguagem HCL. Definir um recurso é direto e legível:

The plan is your seatbelt. It turns "let's hope it works" into "I saw exactly what would happen before it happened". Never apply in production without reading the plan.

Idempotency

A core property of declarative IaC is idempotency: applying the same configuration multiple times always leads to the same state. If the infrastructure is already as you declared it, apply does nothing. This is the opposite of a script that, run twice, creates duplicate resources.

Example in HCL

Terraform uses the HCL language. Defining a resource is straightforward and readable:

resource "aws_instance" "web" {
  ami           = "ami-0abc123"
  instance_type = "t3.micro"
  tags = {
    Name = "servidor-web"
    Env  = "producao"
  }
}

Por que clicar no console não escala

No dia a dia, IaC aparece quando você precisa de ambientes idênticos (dev, staging, produção), recuperar-se de um desastre recriando tudo, ou auditar mudanças. Clicar no console não deixa histórico, não é revisável por um colega num Pull Request e é impossível de reproduzir com fidelidade. Código resolve os três problemas de uma vez — e se conecta naturalmente ao pipeline de CI/CD, que pode aplicar a infraestrutura automaticamente.

Conclusão

Infraestrutura como código traz para o mundo dos servidores as mesmas garantias que o Git trouxe para o software: versionamento, revisão e reprodutibilidade. Entender o modelo declarativo, o papel do state file e o ciclo plan/apply é o que permite gerenciar dezenas de ambientes sem caos — e o que esperam de um DevOps pleno.

Why clicking in the console doesn't scale

Day to day, IaC shows up when you need identical environments (dev, staging, production), need to recover from a disaster by recreating everything, or need to audit changes. Clicking in the console leaves no history, can't be reviewed by a teammate in a Pull Request and is impossible to reproduce faithfully. Code solves all three problems at once — and connects naturally to the CI/CD pipeline, which can apply the infrastructure automatically.

Conclusion

Infrastructure as code brings to the world of servers the same guarantees Git brought to software: versioning, review and reproducibility. Understanding the declarative model, the role of the state file and the plan/apply cycle is what lets you manage dozens of environments without chaos — and what is expected of a mid-level DevOps engineer.

Leia também

Voltar à trilha