Saturday, November 23, 2024
HomeCloudAzureHow to create azure PostgreSQL - Flexible Server using Terraform - Part1

How to create azure PostgreSQL – Flexible Server using Terraform – Part1

As we checked what is Azure PostgreSQL Flexible Server and, in this article, let’s see how to create the flexible via Terraform.

As we all know, terraform is an infrastructure as code tool that lets you define both cloud and on-prem resources in human-readable configuration files that you can version, reuse, and share. You can then use a consistent workflow to provision and manage all your infrastructure throughout its lifecycle. With this saying, most of the organization adopted for hybrid solution and keeping all in single tool, rather maintaining separate code base for each cloud and infra providers.

Let’s check two scenarios in this topic, like one create the flexible from scratch with basic azure resource and other one just creates only components related to flexible server with assuming other resources are already exists.

Use case 1: This section considers you are provisioning Azure PostgreSQL Flexible Server from scratch with all basic azure resources as following

Configure your environment

Azure subscription: This article considers you have azure subscription, if you don’t have please create one from Create Your Azure Free Account Today | Microsoft Azure

Terraform Setup: Follow official page to download and install terraform from https://www.terraform.io/downloads.

Implement the Terraform code

  1. Create a directory in which to test and run the sample Terraform code and make it the current directory.
  2. Create a file named providers.tf and insert the following code:
terraform {
  required_version = ">=1.0"
  
  required_providers {
    azurerm = {
      source = "hashicorp/azurerm"
      version = "~>2.0"
    }
  }
}

provider "azurerm" {
  subscription_id = var.subscription_id
  client_id       = var.client_id
  client_secret   = var.client_secret
  tenant_id       = var.tenant_id
  features {}
}

3. Create a file named main.tf and insert the following code to deploy the PostgreSQL Flexible Server on which the database runs.

resource "foxutech_rg" "rg-name" {
  prefix = var.name
}

resource "azurerm_resource_group" "default" {
  name     = foxutech_rg.rg-name.id
  location = var.location
}

resource "azurerm_virtual_network" "default" {
  name                = "${var.name}-vnet"
  location            = azurerm_resource_group.default.location
  resource_group_name = azurerm_resource_group.default.name
  address_space       = ["10.1.0.0/16"]
}

resource "azurerm_network_security_group" "default" {
  name                = "${var.name}-nsg"
  location            = azurerm_resource_group.default.location
  resource_group_name = azurerm_resource_group.default.name

  security_rule {
    name                       = "foxsec-sec"
    priority                   = 100
    direction                  = "Inbound"
    access                     = "Allow"
    protocol                   = "Tcp"
    source_port_range          = "*"
    destination_port_range     = "*"
    source_address_prefix      = "*"
    destination_address_prefix = "*"
  }
}

resource "azurerm_subnet" "default" {
  name                 = "${var.name}-subnet"
  virtual_network_name = azurerm_virtual_network.default.name
  resource_group_name  = azurerm_resource_group.default.name
  address_prefixes     = ["10.1.1.0/24"]
  service_endpoints    = ["Microsoft.Storage"]

  delegation {
    name = "affs"

    service_delegation {
      name = "Microsoft.DBforPostgreSQL/flexibleServers"

      actions = [
        "Microsoft.Network/virtualNetworks/subnets/join/action",
      ]
    }
  }
}

resource "azurerm_subnet_network_security_group_association" "default" {
  subnet_id                 = azurerm_subnet.default.id
  network_security_group_id = azurerm_network_security_group.default.id
}

resource "azurerm_private_dns_zone" "default" {
  name                = "${var.name}-pdz.postgres.database.azure.com"
  resource_group_name = azurerm_resource_group.default.name

  depends_on = [azurerm_subnet_network_security_group_association.default]
}

resource "azurerm_private_dns_zone_virtual_network_link" "default" {
  name                  = "${var.name}-pdzvnetlink.com"
  private_dns_zone_name = azurerm_private_dns_zone.default.name
  virtual_network_id    = azurerm_virtual_network.default.id
  resource_group_name   = azurerm_resource_group.default.name
}

resource "azurerm_postgresql_flexible_server" "default" {
  name                   = "${var.name}-server"
  resource_group_name    = azurerm_resource_group.default.name
  location               = azurerm_resource_group.default.location
  version                = "12"
  delegated_subnet_id    = azurerm_subnet.default.id
  private_dns_zone_id    = azurerm_private_dns_zone.default.id
  administrator_login    = "var.db_username"
  administrator_password = "var.db_password"
  zone                   = "1"
  storage_mb             = 131072
  sku_name               = "GP_Standard_D2s_v3"
  backup_retention_days  = 7

  depends_on = [azurerm_private_dns_zone_virtual_network_link.default]
}
resource "azurerm_postgresql_flexible_server_database" "default" {
  name      = "${var.name}-db"
  server_id = azurerm_postgresql_flexible_server.default.id
  collation = "en_US.UTF8"
  charset   = "UTF8"
}

4. Create a file named variables.tf and insert the following code, [you can also set environment variable or other secrets which is recommended, as this is for demo/test, i am adding in variables file]

variable "subscription_id" {
        default = "add-subscription-id"
}

variable "client_id" {
        default = "add-client-id"
}

variable "client_secret" {
        default = "add-client-secret"
}

variable "tenant_id" {
        default = "add-tenant-id"
}

variable "name" {
  default     = "foxpsqlfs"
  description = "Prefix of the resource name."
}

variable "location" {
  default     = "eastus"
  description = "Location of the resource."
}

variable "db_username" {
  description = "PSQL DB USername"
  default = "username"
}

variable "db_password" {
  description = "PSQL DB Password"
  default = "P@ssw0rd"
}

5. Create a file named output.tf and insert the following code to output the resource group name, Azure PostgreSQL server name, and Azure PostgreSQL database name

output "resource_group_name" {
    value = azurerm_resource_group.default.name
}

output "azurerm_postgresql_flexible_server" {
    value = azurerm_postgresql_flexible_server.default.name
}

output "postgresql_flexible_server_database_name" {
    value = azurerm_postgresql_flexible_server_database.default.name
}

So far, we have created required files, now lets start terraform actions,

Initialize Terraform

Run terraform init to initialize the Terraform deployment. This command downloads the Azure modules required to manage your Azure resources.

terraform init

Create a Terraform execution plan

Run terraform plan to create an execution plan.

terraform plan -out main.tfplan

Key points:

  • The terraform plan command creates an execution plan, but doesn’t execute it. Instead, it determines what actions are necessary to create the configuration specified in your configuration files. This pattern allows you to verify whether the execution plan matches your expectations before making any changes to actual resources.
  • The optional -out parameter allows you to specify an output file for the plan. Using the -out parameter ensures that the plan you reviewed is exactly what is applied.

Apply a Terraform execution plan

Run terraform apply to apply the execution plan to your cloud infrastructure.

terraform apply main.tfplan

Key points:

  • The terraform apply command above assumes you previously ran terraform plan -out main.tfplan.
  • If you specified a different filename for the -out parameter, use that same filename in the call to terraform apply.
  • If you didn’t use the -out parameter, simply call terraform apply without any parameters.

Verify the results

az postgres flexible-server db show --resource-group <resource_group_name> --server-name <server_name> --database-name <database_name>

Key points:

  • The values for the <resource_group_name>, <server_name>, and <database_name> are displayed in the terraform apply output.

Clean up resources

When you no longer need the resources created via Terraform, do the following steps:

  1. Run terraform plan and specify the destroy flag.
terraform plan -destroy -out main.destroy.tfplan

Key points:

  • The terraform plan command creates an execution plan, but doesn’t execute it. Instead, it determines what actions are necessary to create the configuration specified in your configuration files. This pattern allows you to verify whether the execution plan matches your expectations before making any changes to actual resources.
    • The optional -out parameter allows you to specify an output file for the plan. Using the -out parameter ensures that the plan you reviewed is exactly what is applied.
  • Run terraform apply to apply the execution plan.
terraform apply main.destroy.tfplan

Hope this helps to create the flexible server all the resources. In next article will see how to create just flexible server with considering few resource already exists.

RELATED ARTICLES
- Advertisment -

Most Popular

Recent Comments