# OpenTofu Quick Reference

## Core Architecture
- Graph-based execution: resources form a DAG, parallel where possible
- Provider plugins communicate via gRPC (plugin protocol v5/v6)
- State tracks resource → real-world mapping (JSON format)
- Plan → Apply workflow: always preview before changing

## HCL Essentials
```hcl
terraform {
  required_providers {
    aws = { source = "hashicorp/aws", version = "~> 5.0" }
  }
}

provider "aws" { region = "eu-north-1" }

resource "aws_instance" "web" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t3.micro"
  tags = { Name = "web-server" }
}

variable "env" {
  type    = string
  default = "dev"
}

output "ip" { value = aws_instance.web.public_ip }

data "aws_ami" "latest" {
  most_recent = true
  owners      = ["amazon"]
  filter {
    name   = "name"
    values = ["al2023-ami-*-x86_64"]
  }
}
```

## Resource Lifecycle
- create_before_destroy: new resource before destroying old
- prevent_destroy: block accidental deletion
- ignore_changes: skip drift on specified attributes
- replace_triggered_by: force replacement when dependency changes

## Destroy Order
- Destroy runs in reverse dependency order
- ForceDestroy needed for resources with dependencies
- Deposed instances cleaned up automatically

## State Encryption (OpenTofu-specific)
```hcl
terraform {
  encryption {
    key_provider "pbkdf2" "main" {
      passphrase = var.state_passphrase
    }
    method "aes_gcm" "main" {
      keys = key_provider.pbkdf2.main
    }
    state {
      method   = method.aes_gcm.main
      enforced = true
    }
  }
}
```

## Module Structure
```
modules/
  vpc/
    main.tf
    variables.tf
    outputs.tf
  app/
    main.tf
    variables.tf
    outputs.tf
main.tf          # root module
variables.tf
outputs.tf
terraform.tfvars
```

## Key Commands
- tofu init: initialize providers and modules
- tofu plan: preview changes
- tofu apply: execute changes
- tofu destroy: remove all resources
- tofu state list/show/mv/rm: state management
- tofu import: bring existing resource under management

## Best Practices
- Always use required_providers with version constraints
- Use variables for environment-specific values
- State encryption for sensitive data (OpenTofu feature)
- Modules for reusable infrastructure patterns
- Remote state backend for team collaboration
- Plan file for CI/CD: tofu plan -out=plan.bin && tofu apply plan.bin
