Managing Feature Flags with Terraform: Infrastructure as Code for Feature Management
Learn how to manage feature flags as infrastructure with Terraform — declarative flag definitions, version-controlled rollouts, CI/CD integration, and drift detection.
Feature flags live at the intersection of code and configuration. They control which features are active, who sees them, and how they roll out. Yet most teams manage flags through a UI — clicking buttons in a dashboard, disconnected from the code review and version control processes that govern everything else.
Terraform changes this. By defining feature flags as infrastructure code, you get the same benefits that IaC brought to servers, databases, and networks: version control, code review, drift detection, and reproducible environments.
Why Manage Flags with Terraform?
Version Control
Every flag change goes through a pull request. Reviewers see exactly what's changing — which flags exist, whether they're on, and what they return by default. The git history becomes an audit trail:
commit a3f7b2c Turn on dark mode in production
commit 8e1d9f4 Add the checkout-v2 flag to staging and production
commit 2b4c6a8 Add rate limit flag with 1000 req/min default
The Flaggr provider manages each flag's existence, type, default value and on/off switch. Targeting rules and percentage rollouts aren't part of it: edit rules in the dashboard or through the API, and run rollouts as rollout plans from the dashboard, the API or the MCP server.
Reproducible Environments
Define flags once, apply to multiple environments:
# modules/flags/main.tf
# Each module that uses the provider names its source, or Terraform looks for hashicorp/flaggr.
terraform {
required_providers {
flaggr = {
source = "flaggr-dev/flaggr"
}
}
}
variable "project_id" {}
variable "service_id" {}
variable "environment" {}
variable "checkout_v2_on" { default = false }
resource "flaggr_flag" "new_checkout" {
project_id = var.project_id
service_id = var.service_id
key = "release-checkout-v2"
name = "Checkout V2"
type = "boolean"
environment = var.environment
enabled = true
default_value = jsonencode(var.checkout_v2_on)
}# environments/staging/main.tf
module "flags" {
source = "../../modules/flags"
project_id = module.project.id
service_id = module.service.id
environment = "staging"
checkout_v2_on = true # On for everyone in staging
}
# environments/production/main.tf
module "flags" {
source = "../../modules/flags"
project_id = module.project.id
service_id = module.service.id
environment = "production"
checkout_v2_on = false # Off in production until its rollout plan finishes
}Drift Detection
terraform plan shows you when the actual flag state doesn't match your code. Someone toggled a flag in the UI? Terraform catches it:
~ resource "flaggr_flag" "dark_mode" {
~ enabled = true -> false # UI change detected
~ default_value = "true" -> "false"
}
Drift detection becomes especially valuable in organizations where multiple people can modify flags. A common scenario: an on-call engineer disables a flag via the dashboard during an incident (the right call in the moment), but forgets to update the Terraform configuration afterward. The next terraform plan surfaces this discrepancy, prompting the team to either codify the change or revert it intentionally.
You can automate drift detection by running terraform plan on a schedule (for example, a daily cron job in your CI system) and alerting the team when drift is detected. This ensures that the Terraform configuration remains the canonical source of truth for flag state, even when emergency changes are made through the UI:
# .github/workflows/drift-check.yml
name: Flag Drift Detection
on:
schedule:
- cron: '0 9 * * 1-5' # Weekdays at 9 AM
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- run: terraform init
working-directory: terraform/flags
- run: |
terraform plan -detailed-exitcode -no-color 2>&1 | tee plan.txt
if [ $? -eq 2 ]; then
echo "::warning::Flag drift detected! Review terraform/flags for UI changes."
fi
working-directory: terraform/flags
env:
TF_VAR_flaggr_api_token: ${{ secrets.FLAGGR_API_TOKEN }}For more on flag lifecycle management, including naming conventions and staleness detection that complement Terraform-based workflows, see our feature flag best practices guide.
CI/CD Integration
Flag changes flow through the same pipeline as infrastructure changes. Apply flags alongside the services that use them:
# .github/workflows/deploy.yml
jobs:
deploy:
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- name: Deploy infrastructure
run: terraform apply -auto-approve
working-directory: terraform/infrastructure
- name: Apply feature flags
run: terraform apply -auto-approve
working-directory: terraform/flagsGetting Started with the Flaggr Terraform Provider
Installing the Provider
The provider is public at github.com/flaggr-dev/terraform-provider-flaggr. Its Terraform Registry address is flaggr-dev/flaggr, but the Registry doesn't list it yet, so terraform init can't download it from there. Until it does, install it from the v0.1.1 GitHub release:
- Download
terraform-provider-flaggr_0.1.1_<os>_<arch>.zipfor your platform andterraform-provider-flaggr_0.1.1_SHA256SUMS, and check the zip:shasum -a 256 --ignore-missing -c terraform-provider-flaggr_0.1.1_SHA256SUMS. - Put the zip, as it is, in
~/.terraform.d/plugins/registry.terraform.io/flaggr-dev/flaggr/. Terraform looks for providers in that directory by default, so no CLI configuration is needed, unless your CLI configuration has its ownprovider_installationblock: then add the directory to it as afilesystem_mirror. Do the same on every machine that runs Terraform, CI runners included.
If you commit .terraform.lock.hcl, put the zip of every platform that runs Terraform in that directory and record all their hashes. Otherwise terraform init on another platform, such as a Linux CI runner, fails the lock file's checksum check:
terraform providers lock -fs-mirror="$HOME/.terraform.d/plugins" -platform=linux_amd64 -platform=darwin_arm64In CI, a step like this before terraform init installs the provider on a Linux runner:
dir="$HOME/.terraform.d/plugins/registry.terraform.io/flaggr-dev/flaggr"
url="https://github.com/flaggr-dev/terraform-provider-flaggr/releases/download/v0.1.1"
mkdir -p "$dir" && cd "$dir"
curl -fsSLO "$url/terraform-provider-flaggr_0.1.1_linux_amd64.zip"
curl -fsSL "$url/terraform-provider-flaggr_0.1.1_SHA256SUMS" | sha256sum --ignore-missing -c -The infrastructure as code guide has the same steps.
To build it from source instead, run make build in a clone of the repository and point a dev_overrides block in your Terraform CLI configuration at the build, as the provider's README describes.
Provider Configuration
Declare the provider by its Registry address and configure it with a personal access token:
terraform {
required_providers {
flaggr = {
source = "flaggr-dev/flaggr"
version = "~> 0.1"
}
}
}
provider "flaggr" {
api_url = "https://flaggr.dev"
api_token = var.flaggr_api_token # personal access token (fgp_...)
}Creating a Project and Service
resource "flaggr_project" "main" {
name = "My Application"
slug = "my-app"
}
resource "flaggr_service" "api" {
project_id = flaggr_project.main.id
name = "API Service"
description = "Backend API service"
}
resource "flaggr_service" "web" {
project_id = flaggr_project.main.id
name = "Web Frontend"
description = "React web application"
}Defining Feature Flags
# Boolean flag (default_value is JSON: use jsonencode)
resource "flaggr_flag" "dark_mode" {
project_id = flaggr_project.main.id
service_id = flaggr_service.web.id
key = "release-dark-mode"
name = "Dark Mode"
description = "Enable dark mode theme"
type = "boolean"
environment = "production"
enabled = true
default_value = jsonencode(false)
}
# String flag for variant testing
resource "flaggr_flag" "cta_text" {
project_id = flaggr_project.main.id
service_id = flaggr_service.web.id
key = "experiment-cta-text"
name = "CTA Button Text"
type = "string"
environment = "production"
enabled = true
default_value = jsonencode("Get Started")
}
# Number flag for configuration
resource "flaggr_flag" "rate_limit" {
project_id = flaggr_project.main.id
service_id = flaggr_service.api.id
key = "ops-rate-limit"
name = "API Rate Limit"
type = "number"
environment = "production"
enabled = true
default_value = jsonencode(1000)
}Setting Up Alerting
resource "flaggr_alert_channel" "slack" {
project_id = flaggr_project.main.id
name = "Engineering Slack"
type = "slack"
config = jsonencode({
webhookUrl = var.slack_webhook_url
})
}
resource "flaggr_alert_rule" "high_error_rate" {
project_id = flaggr_project.main.id
name = "High Error Rate"
severity = "critical"
condition_type = "error_rate" # percent: 5 = 5%
threshold = 5.0
window_minutes = 5
channels = jsonencode([
{
channelId = flaggr_alert_channel.slack.id
channelName = flaggr_alert_channel.slack.name
}
])
}Using Data Sources
Read existing resources for reference in other configurations:
data "flaggr_project" "existing" {
slug = "my-app"
}
data "flaggr_service" "api" {
id = "svc_123"
}
data "flaggr_flag" "checkout" {
key = "release-checkout-v2"
service_id = data.flaggr_service.api.id
environment = "production"
}
output "checkout_enabled" {
value = data.flaggr_flag.checkout.enabled
}Patterns for Flag Management
Environment Promotion
Use Terraform workspaces or modules to promote flag configurations across environments:
# variables.tf
variable "env_config" {
type = map(object({
on = bool
enabled = bool
}))
default = {
development = { on = true, enabled = true }
staging = { on = true, enabled = true }
production = { on = false, enabled = true }
}
}
resource "flaggr_flag" "feature" {
for_each = var.env_config
project_id = flaggr_project.main.id
service_id = flaggr_service.api.id
key = "release-new-feature"
name = "New Feature"
type = "boolean"
environment = each.key
enabled = each.value.enabled
default_value = jsonencode(each.value.on)
}Release via PR
Ship a flag through pull requests, one environment at a time:
# PR #1: "Add checkout-v2, on in staging" — the flag exists everywhere, on only in staging
# PR #2: "Turn on checkout-v2 in production" — the production flag's default becomes true
default_value = jsonencode(true)
# PR #3: "Remove checkout-v2 flag" — delete the resource once the code no longer reads itEach change is reviewed, approved, and has a clear audit trail in git. To go through percentage stages instead of switching everyone at once, run a rollout plan, which advances on its own guardrails.
Importing Existing Flags
Already have flags created through the UI? Import them into Terraform state:
# Import a project
terraform import flaggr_project.main <project-id>
# Import a service
terraform import flaggr_service.api <service-id>
# Import a flag (format: key:serviceId:environment)
terraform import flaggr_flag.dark_mode "release-dark-mode:svc_123:production"
# Import an alert channel (format: projectId:channelId)
terraform import flaggr_alert_channel.slack "proj_123:ch_456"After importing, run terraform plan to verify the state matches your configuration.
Flag Lifecycle as Code
Encode your team's flag lifecycle policy in Terraform:
locals {
# Flags that have been on for everyone for more than 30 days should be removed
# (var.flags: your own map of { on = bool, on_since = RFC 3339 timestamp })
stale_flags = {
for k, v in var.flags : k => v
if v.on && timecmp(v.on_since, timeadd(timestamp(), "-720h")) < 0
}
}
# Output stale flags for cleanup review
output "flags_pending_removal" {
value = [for k, v in local.stale_flags : k]
}CI/CD Integration Patterns
GitHub Actions
name: Feature Flag Deployment
on:
push:
paths: ['terraform/flags/**']
branches: [main]
pull_request:
paths: ['terraform/flags/**']
jobs:
plan:
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- run: terraform init
working-directory: terraform/flags
- run: terraform plan -no-color
working-directory: terraform/flags
env:
TF_VAR_flaggr_api_token: ${{ secrets.FLAGGR_API_TOKEN }}
apply:
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- run: terraform init && terraform apply -auto-approve
working-directory: terraform/flags
env:
TF_VAR_flaggr_api_token: ${{ secrets.FLAGGR_API_TOKEN }}Until the Terraform Registry lists the provider, each of these jobs, like the drift check above, needs the install step from Installing the Provider before terraform init.
GitOps with Atlantis
For teams using Atlantis for Terraform automation:
# atlantis.yaml
projects:
- dir: terraform/flags
workflow: flags
autoplan:
when_modified: ["*.tf", "*.tfvars"]
workflows:
flags:
plan:
steps:
- init
- plan
apply:
steps:
- applyWhen to Use Terraform vs the UI
Terraform excels for:
- Production flag changes — every change reviewed and auditable
- Environment setup — reproducible flag configurations across environments
- Release steps — turning flags on, environment by environment, via PRs
- Team onboarding — new services get standard flags automatically
The UI is better for:
- Rapid iteration during development — toggling flags while debugging
- Emergency kill switches — when seconds matter, click the button
- Exploration — understanding flag state across services
- Non-technical stakeholders — product managers reviewing flag status
The best approach combines both: Terraform for production governance, the UI for development and emergency response. Flaggr's drift detection (via terraform plan) catches UI changes that should be codified.
Getting Started
- Generate a personal access token under Profile → Personal access tokens, with the admin tier if Terraform will create or change projects
- Install the provider from its GitHub release, as in Installing the Provider: the Terraform Registry doesn't list it yet
- Import existing resources: Use
terraform importto bring current flags under management - Start with non-critical flags: Practice the workflow before managing production-critical flags
The infrastructure as code guide covers the provider's resources, authentication and the API-driven alternatives.
Read the infrastructure as code guide for setup instructions.