Azure Azure - Terraform templates

Postgresql

Last updated: May 18, 2025
In this Terraform configuration, we create an Azure PostgreSQL Flexible Server, which is a managed database service optimized for PostgreSQL workloads. The choice of Flexible Server over Single Server is due to its enhanced control over maintenance windows, high availability options, and better cost management.

The server is named using a combination of environment and solution prefixes to ensure uniqueness and clarity in resource identification. We specify PostgreSQL version 13, which is a stable and widely supported version, balancing performance and compatibility.

For administrator credentials, we generate a strong, random password using the random_password resource, which enhances security by avoiding hardcoded secrets. The administrator login is set to a generic but clear name pgadmin.

We select the SKU B_Standard_B1ms, a cost-effective option suitable for development and testing environments. Storage is set to 32 GB, which is a reasonable starting point for many workloads, with the ability to scale as needed.

Backup retention is configured for 7 days, providing a balance between data protection and cost. Geo-redundant backups and high availability are disabled to optimize costs, but these can be enabled for production workloads requiring higher resilience.

Network access is enabled publicly for simplicity, but in production scenarios, it is recommended to restrict access using virtual network integration or firewall rules for enhanced security.

resource "random_password" "pg_password" {
  length  = 16
  special = true
}

resource "azurerm_postgresql_flexible_server" "postgresql" {
  name                = "${local.resource_prefix_short}-pg"
  resource_group_name = azurerm_resource_group.rg.name
  location            = azurerm_resource_group.rg.location
  version             = "13"
  administrator_login = "pgadmin"
  administrator_password = random_password.pg_password.result
  sku_name            = "B_Standard_B1ms"
  storage_mb          = 32768
  backup_retention_days = 7
  delegated_subnet_id = null
  tags                = local.tags

  public_network_access_enabled = true
}