Terraform tem três tipos de valores parametrizáveis: variables (entrada), locals (valores intermediários) e outputs (saída).
Input Variables
Declaradas em variables.tf, recebem valores externamente:
variable "ambiente" {
description = "Ambiente de deploy (dev, staging, prod)"
type = string
default = "dev"
validation {
condition = contains(["dev", "staging", "prod"], var.ambiente)
error_message = "Ambiente deve ser dev, staging ou prod."
}
}
variable "instance_type" {
type = string
}Tipos disponíveis: string, number, bool, list(type), map(type), object({}), any
Passando valores
# Via arquivo tfvars (recomendado)
terraform apply -var-file="prod.tfvars"
# Via CLI
terraform apply -var="ambiente=prod"
# Via variável de ambiente
export TF_VAR_ambiente=prod# prod.tfvars
ambiente = "prod"
instance_type = "t3.medium"Locals
Valores calculados internamente, não expostos externamente:
locals {
prefixo = "${var.projeto}-${var.ambiente}"
tags_padrao = {
Projeto = var.projeto
Ambiente = var.ambiente
ManagedBy = "terraform"
}
}
resource "aws_s3_bucket" "assets" {
bucket = "${local.prefixo}-assets"
tags = local.tags_padrao
}Outputs
Expõem valores após o apply, úteis para passar informações entre módulos ou exibir endpoints:
output "bucket_url" {
description = "URL do bucket S3"
value = "https://${aws_s3_bucket.assets.bucket}.s3.amazonaws.com"
}
output "instance_ip" {
description = "IP público da instância"
value = aws_instance.app.public_ip
sensitive = true # Não exibe no terminal
}Ver também: terraform-resources | terraform | terraform-cloud-aws