# Infrastructure as Code (Terraform, OpenTofu & Pulumi)

Manage services, schedules, escalation policies, rotations, and integration keys declaratively using the official [OnCallAlert Terraform Provider](https://registry.terraform.io/providers/OnCallAlert/oncallalert/latest). The provider communicates directly with your self-hosted server using an administrator API token.

## Step 1: Create an Admin API Token

1. Sign in to your OnCallAlert server as an administrator.
2. Navigate to your user profile and locate **API Tokens**.
3. Click **Create Token**, select scope **Admin**, and set an expiration duration (up to 365 days).
4. Copy the secret token string immediately (shown only once).

## Step 2: Configure Provider

### Terraform / OpenTofu

```hcl
terraform {
  required_providers {
    oncallalert = {
      source  = "OnCallAlert/oncallalert"
      version = "~> 1.0"
    }
  }
}

provider "oncallalert" {
  url   = "https://oncall.yourcompany.com" # or ONCALLALERT_URL env var
  token = var.oncallalert_token            # or ONCALLALERT_TOKEN env var
}
```

## Step 3: Define Infrastructure Resources

```hcl
data "oncallalert_user" "lead" {
  email = "lead@example.com"
}

resource "oncallalert_rotation" "primary_rotation" {
  name       = "Backend Primary Rotation"
  time_zone  = "America/New_York"
  start      = "2026-01-01T09:00:00-05:00"
  type       = "weekly"
  user_ids   = [data.oncallalert_user.lead.id]
}

resource "oncallalert_escalation_policy" "primary_policy" {
  name = "Production API Policy"
  steps = [
    {
      delay_minutes = 5
      actions = [
        {
          type = "builtin-rotation"
          args = { rotation_id = oncallalert_rotation.primary_rotation.id }
        }
      ]
    }
  ]
}

resource "oncallalert_service" "api_service" {
  name                 = "Core API"
  escalation_policy_id = oncallalert_escalation_policy.primary_policy.id
  description          = "Public REST API service"
}

resource "oncallalert_integration_key" "grafana" {
  service_id = oncallalert_service.api_service.id
  name       = "Grafana Alerts"
  type       = "grafana"
}
```

## Supported Resources

- `oncallalert_user`
- `oncallalert_service`
- `oncallalert_escalation_policy`
- `oncallalert_rotation`
- `oncallalert_schedule`
- `oncallalert_schedule_rule`
- `oncallalert_override`
- `oncallalert_integration_key`
- `oncallalert_heartbeat_monitor`
