> ## Documentation Index
> Fetch the complete documentation index at: https://www.qovery.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Advanced Patterns

> Manage Qovery at scale with Terraform modules, one workspace per environment, remote state, variable files and conditional resources.

## Overview

This guide covers Terraform patterns for managing Qovery resources at scale: modules, workspaces, remote state, variable files, lists built from variables and conditional resources.

## Reusable Modules

Organize your Terraform code with reusable modules for consistent deployments.

### Module Structure

```
terraform-qovery/
├── main.tf
├── variables.tf
├── outputs.tf
└── modules/
    ├── environment/
    │   ├── main.tf
    │   ├── variables.tf
    │   └── outputs.tf
    ├── application/
    │   ├── main.tf
    │   ├── variables.tf
    │   └── outputs.tf
    └── database/
        ├── main.tf
        ├── variables.tf
        └── outputs.tf
```

### Application Module

This module declares its inputs, the application and its outputs in one file for brevity. A module that uses the Qovery provider declares it in its own `required_providers` block; otherwise Terraform looks for a `hashicorp/qovery` provider.

**modules/application/main.tf**

```hcl theme={null}
terraform {
  required_providers {
    qovery = {
      source  = "qovery/qovery"
      version = "~> 1.0"
    }
  }
}

variable "environment_id" {
  description = "Environment ID"
  type        = string
}

variable "name" {
  description = "Application name"
  type        = string
}

variable "git_url" {
  description = "Git repository URL"
  type        = string
}

variable "git_branch" {
  description = "Git branch"
  type        = string
  default     = "main"
}

variable "cpu" {
  description = "CPU allocation in millicores"
  type        = number
  default     = 500
}

variable "memory" {
  description = "Memory allocation in MB"
  type        = number
  default     = 512
}

variable "port" {
  description = "Internal application port"
  type        = number
  default     = 8080
}

variable "publicly_accessible" {
  description = "Make application publicly accessible"
  type        = bool
  default     = true
}

resource "qovery_application" "app" {
  environment_id = var.environment_id
  name           = var.name

  git_repository = {
    url    = var.git_url
    branch = var.git_branch
  }

  build_mode      = "DOCKER"
  dockerfile_path = "Dockerfile"

  cpu    = var.cpu
  memory = var.memory

  ports = [{
    internal_port       = var.port
    external_port       = var.publicly_accessible ? 443 : null
    protocol            = "HTTP"
    publicly_accessible = var.publicly_accessible
  }]

  healthchecks = {
    readiness_probe = {
      type = {
        tcp = {
          port = var.port
        }
      }
      initial_delay_seconds = 30
      period_seconds        = 10
      timeout_seconds       = 5
      success_threshold     = 1
      failure_threshold     = 3
    }
  }

  auto_deploy = var.git_branch != "main"
}

output "id" {
  value       = qovery_application.app.id
  description = "Application ID"
}

output "external_host" {
  value       = qovery_application.app.external_host
  description = "Application external hostname"
}

output "internal_host" {
  value       = qovery_application.app.internal_host
  description = "Application internal hostname"
}
```

### Using the Module

The root configuration takes the IDs of an existing project and cluster as input variables. See [Find resource IDs](https://www.qovery.com/docs/terraform-provider/overview.md#find-resource-ids).

**main.tf**

```hcl theme={null}
terraform {
  required_providers {
    qovery = {
      source  = "qovery/qovery"
      version = "~> 1.0"
    }
  }
}

# Reads the API token from the QOVERY_API_TOKEN environment variable.
provider "qovery" {}

variable "project_id" {
  description = "ID of an existing project"
  type        = string
}

variable "cluster_id" {
  description = "ID of the cluster that runs the environment"
  type        = string
}

resource "qovery_environment" "prod" {
  project_id = var.project_id
  cluster_id = var.cluster_id
  name       = "production"
  mode       = "PRODUCTION"
}

# Deploy API using module
module "api" {
  source = "./modules/application"

  environment_id = qovery_environment.prod.id
  name           = "api"
  git_url        = "https://github.com/my-org/api.git"
  git_branch     = "main"
  cpu            = 1000
  memory         = 1024
  port           = 3000
}

# Deploy frontend using module
module "frontend" {
  source = "./modules/application"

  environment_id = qovery_environment.prod.id
  name           = "frontend"
  git_url        = "https://github.com/my-org/frontend.git"
  git_branch     = "main"
  cpu            = 500
  memory         = 512
  port           = 8080
}

# Deploy admin using module
module "admin" {
  source = "./modules/application"

  environment_id      = qovery_environment.prod.id
  name                = "admin"
  git_url             = "https://github.com/my-org/admin.git"
  git_branch          = "main"
  cpu                 = 250
  memory              = 256
  port                = 8080
  publicly_accessible = false # Internal only
}

# Creating the services does not deploy them: this resource deploys the environment.
resource "qovery_deployment" "prod" {
  environment_id = qovery_environment.prod.id
  desired_state  = "RUNNING"

  depends_on = [module.api, module.frontend, module.admin]
}
```

## Terraform Workspaces

Use workspaces to manage multiple environments with a single configuration: each workspace has its own state. The configuration reads the workspace name from `terraform.workspace` and looks up the settings of that environment.

The [multi-environment example](https://www.qovery.com/docs/terraform-provider/multi-environment.md) uses the same kind of settings map with `for_each` and shows the complete application. With workspaces, you index the map with the workspace name instead.

### Workspace Configuration

```hcl theme={null}
locals {
  # Get current workspace name
  environment = terraform.workspace

  # Environment-specific configuration
  config = {
    dev = {
      mode             = "DEVELOPMENT"
      managed_database = false
    }
    staging = {
      mode             = "STAGING"
      managed_database = false
    }
    production = {
      mode             = "PRODUCTION"
      managed_database = true
    }
  }

  # Get current environment config
  current_config = local.config[local.environment]
}

resource "qovery_environment" "env" {
  project_id = var.project_id
  cluster_id = var.cluster_id
  name       = local.environment
  mode       = local.current_config.mode
}

# PostgreSQL in a container on the cluster, outside production
resource "qovery_database" "db" {
  count = local.current_config.managed_database ? 0 : 1

  environment_id = qovery_environment.env.id
  name           = "database"
  type           = "POSTGRESQL"
  version        = "16"
  mode           = "CONTAINER"
  accessibility  = "PRIVATE"
  storage        = 10
}

# Amazon RDS for PostgreSQL from the service catalog, in production. Requires an AWS cluster.
resource "qovery_blueprint" "db" {
  count = local.current_config.managed_database ? 1 : 0

  environment_id = qovery_environment.env.id
  name           = "database"
  blueprint      = "AWS/postgres/17"

  variables = {
    # Also names the RDS instance: it must be unique in the AWS account and region.
    db_name = "app_${local.environment}"
  }
}

# Declare the services the same way, with values from local.current_config.
```

Production uses a managed database, created from a blueprint of the [service catalog](https://www.qovery.com/docs/configuration/blueprints.md) with [`qovery_blueprint`](https://registry.terraform.io/providers/qovery/qovery/latest/docs/resources/blueprint). The Amazon RDS blueprint needs an AWS cluster. [Application with Database](https://www.qovery.com/docs/terraform-provider/application-with-database.md#use-a-managed-database) shows how an application connects to it.

### Using Workspaces

The configuration only knows the `dev`, `staging` and `production` workspaces: create them before you apply, and do not apply in the `default` workspace.

```bash theme={null}
# Create workspaces
terraform workspace new dev
terraform workspace new staging
terraform workspace new production

# List workspaces
terraform workspace list

# Deploy to development
terraform workspace select dev
terraform apply

# Deploy to staging
terraform workspace select staging
terraform apply

# Deploy to production
terraform workspace select production
terraform apply

# Show current workspace
terraform workspace show
```

## Remote State Management

Store Terraform state remotely for team collaboration.

### S3 Backend

`use_lockfile`, which locks the state in the bucket itself, needs Terraform 1.10 or later.

```hcl theme={null}
terraform {
  backend "s3" {
    bucket       = "my-terraform-state"
    key          = "qovery/terraform.tfstate"
    region       = "us-east-1"
    encrypt      = true
    use_lockfile = true
  }

  required_providers {
    qovery = {
      source  = "qovery/qovery"
      version = "~> 1.0"
    }
  }
}
```

`use_lockfile = true` locks the state with a lock file in the bucket, so you do not need a DynamoDB table. Enable versioning on the bucket to recover an earlier version of the state.

### Terraform Cloud

```hcl theme={null}
terraform {
  cloud {
    organization = "my-org"

    workspaces {
      name = "qovery-production"
    }
  }

  required_providers {
    qovery = {
      source  = "qovery/qovery"
      version = "~> 1.0"
    }
  }
}
```

### Initialize Backend

```bash theme={null}
# Initialize backend
terraform init

# Migrate existing state
terraform init -migrate-state
```

## Variable Files

Organize variables per environment using `.tfvars` files.

### Directory Structure

```
terraform/
├── main.tf
├── variables.tf
├── outputs.tf
└── environments/
    ├── dev.tfvars
    ├── staging.tfvars
    └── production.tfvars
```

### variables.tf

```hcl theme={null}
variable "environment_name" {
  description = "Environment name"
  type        = string
}

variable "environment_mode" {
  description = "Environment mode"
  type        = string
}

variable "cpu" {
  description = "CPU allocation"
  type        = number
}

variable "memory" {
  description = "Memory allocation"
  type        = number
}

variable "replicas" {
  description = "Number of replicas"
  type        = number
}
```

### environments/production.tfvars

```hcl theme={null}
environment_name = "production"
environment_mode = "PRODUCTION"
cpu              = 1000
memory           = 1024
replicas         = 3
```

### environments/dev.tfvars

```hcl theme={null}
environment_name = "dev"
environment_mode = "DEVELOPMENT"
cpu              = 250
memory           = 256
replicas         = 1
```

Keep the API token out of these files: the provider reads it from the `QOVERY_API_TOKEN` environment variable.

### Deploy with Variable Files

```bash theme={null}
# Deploy to development
terraform apply -var-file="environments/dev.tfvars"

# Deploy to production
terraform apply -var-file="environments/production.tfvars"
```

Both commands use the same state unless each environment has its own backend configuration or workspace.

## Lists from Variables

`ports`, `environment_variables` and the other list attributes of the Qovery resources are nested attributes, not blocks, so `dynamic` blocks do not apply to them. Assign a list directly, or build one with a `for` expression.

```hcl theme={null}
variable "ports" {
  description = "Application ports"
  type = list(object({
    internal_port       = number
    external_port       = number
    protocol            = string
    publicly_accessible = bool
  }))
  default = [
    {
      internal_port       = 8080
      external_port       = 443
      protocol            = "HTTP"
      publicly_accessible = true
    }
  ]
}

variable "environment_variables" {
  description = "Environment variables of the application"
  type        = map(string)
  default = {
    LOG_LEVEL = "info"
  }
}

resource "qovery_application" "app" {
  environment_id = qovery_environment.prod.id
  name           = "my-app"

  git_repository = {
    url    = "https://github.com/my-org/app.git"
    branch = "main"
  }

  build_mode      = "DOCKER"
  dockerfile_path = "Dockerfile"

  # A list from a variable
  ports = var.ports

  # A list built from a map with a for expression
  environment_variables = [
    for key, value in var.environment_variables : {
      key   = key
      value = value
    }
  ]

  healthchecks = {
    readiness_probe = {
      type = {
        tcp = {
          port = var.ports[0].internal_port
        }
      }
      initial_delay_seconds = 30
      period_seconds        = 10
      timeout_seconds       = 5
      success_threshold     = 1
      failure_threshold     = 3
    }
  }
}
```

## Conditional Resources

Create resources conditionally based on variables.

```hcl theme={null}
variable "enable_database" {
  description = "Enable database deployment"
  type        = bool
  default     = true
}

variable "enable_redis" {
  description = "Enable Redis deployment"
  type        = bool
  default     = false
}

# Amazon RDS for PostgreSQL from the service catalog
resource "qovery_blueprint" "postgres" {
  count = var.enable_database ? 1 : 0

  environment_id = qovery_environment.prod.id
  name           = "postgres"
  blueprint      = "AWS/postgres/17"

  variables = {
    # Also names the RDS instance: it must be unique in the AWS account and region.
    db_name = "app"
  }
}

# Amazon ElastiCache for Redis from the service catalog
resource "qovery_blueprint" "redis" {
  count = var.enable_redis ? 1 : 0

  environment_id = qovery_environment.prod.id
  name           = "redis"
  blueprint      = "AWS/redis/7"

  variables = {
    # Also names the ElastiCache cluster: it must be unique in the AWS account and region.
    redis_name = "my-app-redis"
  }
}
```

These managed databases are blueprints of the [service catalog](https://www.qovery.com/docs/configuration/blueprints.md), created with [`qovery_blueprint`](https://registry.terraform.io/providers/qovery/qovery/latest/docs/resources/blueprint). Both blueprints need an AWS cluster. `db_name` and `redis_name` are the only variables they require; the others use their catalog defaults.

## Best Practices

> [accordion] Use Version Constraints
>
> Pin the provider major version, so that a new major release cannot introduce breaking changes without an explicit upgrade. The provider is tested against Terraform 1.15; earlier versions are expected to work but are not tested.
>
> ```hcl theme={null}
> terraform {
>   required_providers {
>     qovery = {
>       source  = "qovery/qovery"
>       version = "~> 1.0" # Allows 1.x updates, not 2.0
>     }
>   }
> }
> ```

> [accordion] Separate State Per Environment
>
> Use different state files for each environment to prevent accidental changes:
>
> * Different S3 keys: `env/dev/terraform.tfstate`, `env/prod/terraform.tfstate`
> * Different Terraform Cloud workspaces
> * Different backend configurations

> [accordion] Use Data Sources
>
> Read an existing resource by its ID instead of copying its attributes into the configuration. Data sources look up resources by `id`, not by name:
>
> ```hcl theme={null}
> data "qovery_project" "existing" {
>   id = var.project_id
> }
>
> output "project_name" {
>   value = data.qovery_project.existing.name
> }
> ```

> [accordion] Protect Production
>
> Add lifecycle rules to prevent accidental deletion:
>
> ```hcl theme={null}
> resource "qovery_blueprint" "prod_database" {
>   # ... configuration ...
>
>   lifecycle {
>     prevent_destroy = true
>   }
> }
> ```

> [accordion] Share Labels with a Labels Group
>
> Declare common Kubernetes labels once in a labels group, then attach the group to each service with `labels_group_ids`:
>
> ```hcl theme={null}
> resource "qovery_labels_group" "common" {
>   organization_id = var.organization_id
>   name            = "my-project"
>
>   labels = [
>     {
>       key                         = "project"
>       value                       = "my-project"
>       propagate_to_cloud_provider = false
>     },
>     {
>       key                         = "managed-by"
>       value                       = "terraform"
>       propagate_to_cloud_provider = false
>     }
>   ]
> }
>
> # On each service:
> #   labels_group_ids = [qovery_labels_group.common.id]
> ```

## Next Steps

> [card] [Basic Application](https://www.qovery.com/docs/terraform-provider/basic-application.md)
>
> Start with a simple application

> [card] [Multi-Environment](https://www.qovery.com/docs/terraform-provider/multi-environment.md)
>
> Deploy to multiple environments

> [card] [Provider Documentation](https://registry.terraform.io/providers/qovery/qovery/latest/docs)
>
> Complete provider reference

> [card] [Terraform Documentation](https://developer.hashicorp.com/terraform/docs)
>
> Official Terraform documentation


## Related topics

- [Airbyte Deployment](https://www.qovery.com/docs/terraform-provider/airbyte-deployment.md)
- [Linking Services Together](https://www.qovery.com/docs/terraform-provider/linking-services.md)
- [Multi-Environment Setup](https://www.qovery.com/docs/terraform-provider/multi-environment.md)
- [Terraform Provider](https://www.qovery.com/docs/terraform-provider/overview.md)
- [Service Advanced Settings](https://www.qovery.com/docs/configuration/service-advanced-settings.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.