AI Skill Library

Terraform IaC

HCL syntax, providers, resources, state, modules, workspaces.

terraformdevopscloudiac
# Terraform IaC

## Core concepts
- **Provider**: plugin for a cloud/service (AWS, GCP, K8s).
- **Resource**: infrastructure object managed by Terraform.
- **Data source**: read existing infra (not managed by TF).
- **State**: `.tfstate` maps config to real-world resources.
- **Module**: reusable group of resources.

## Basic config
```hcl
terraform {
  required_providers {
    aws = { source = "hashicorp/aws", version = "~> 5.0" }
  }
  backend "s3" {
    bucket = "my-tfstate"
    key    = "prod/terraform.tfstate"
    region = "us-east-1"
  }
}
provider "aws" { region = "us-east-1" }

variable "env" { default = "prod" }

resource "aws_s3_bucket" "assets" {
  bucket = "my-assets-prod"
  tags   = { Environment = var.env }
}

output "bucket_name" { value = aws_s3_bucket.assets.bucket }
```

## Workflow
```bash
terraform init     # download providers, init backend
terraform plan     # preview changes
terraform apply    # apply
terraform destroy
terraform output
```

## State management
- Remote state (S3 + DynamoDB lock) mandatory for teams.
- `terraform state list` / `terraform state show <resource>`
- Import: `terraform import aws_s3_bucket.x bucket-name`

## Modules
```hcl
module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "5.0.0"
  name = "main"
  cidr = "10.0.0.0/16"
}
```

## Best practices
- Pin provider versions. Use `locals` for computed values.
- `terraform fmt` + `terraform validate` in CI.
- Post `plan` output as PR comment.

API: /api/skills/terraform-iac