Quickstart: Use Terraform to create an Azure Database for MySQL - Flexible Server

APPLIES TO: Azure Database for MySQL - Flexible Server

Article tested with the following Terraform and Terraform provider versions:

Azure Database for MySQL - Flexible Server is a managed service that you use to run, manage, and scale highly available MySQL databases in the cloud. You can use an Azure Resource Manager template (ARM template) to provision a flexible server to deploy multiple servers or multiple databases on a server.

This article shows how to use Terraform to deploy an Azure MySQL Flexible Server Database in a virtual network (VNet).

In this article, you learn how to:

Note

The example code in this article is located in the Azure Terraform GitHub repo.

Prerequisites

Implement the Terraform code

  1. Create a directory in which to test 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 = "~>3.0"
        }
    
        random = {
          source  = "hashicorp/random"
          version = "~>3.0"
        }
      }
    }
    
    provider "azurerm" {
      features {}
    }
    
  3. Create a file named main.tf and insert the following code:

    # Generate random resource group name
    resource "random_pet" "rg_name" {
      prefix = var.resource_group_name_prefix
    }
    
    resource "azurerm_resource_group" "rg" {
      location = var.resource_group_location
      name     = random_pet.rg_name.id
    }
    
    # Generate random value for the name
    resource "random_string" "name" {
      length  = 8
      lower   = true
      numeric = false
      special = false
      upper   = false
    }
    
    # Generate random value for the login password
    resource "random_password" "password" {
      length           = 8
      lower            = true
      min_lower        = 1
      min_numeric      = 1
      min_special      = 1
      min_upper        = 1
      numeric          = true
      override_special = "_"
      special          = true
      upper            = true
    }
    
    # Manages the Virtual Network
    resource "azurerm_virtual_network" "default" {
      address_space       = ["10.0.0.0/16"]
      location            = azurerm_resource_group.rg.location
      name                = "vnet-${random_string.name.result}"
      resource_group_name = azurerm_resource_group.rg.name
    }
    
    # Manages the Subnet
    resource "azurerm_subnet" "default" {
      address_prefixes     = ["10.0.2.0/24"]
      name                 = "subnet-${random_string.name.result}"
      resource_group_name  = azurerm_resource_group.rg.name
      virtual_network_name = azurerm_virtual_network.default.name
      service_endpoints    = ["Microsoft.Storage"]
    
      delegation {
        name = "fs"
    
        service_delegation {
          name    = "Microsoft.DBforMySQL/flexibleServers"
          actions = [
            "Microsoft.Network/virtualNetworks/subnets/join/action",
          ]
        }
      }
    }
    
    # Enables you to manage Private DNS zones within Azure DNS
    resource "azurerm_private_dns_zone" "default" {
      name                = "${random_string.name.result}.mysql.database.azure.com"
      resource_group_name = azurerm_resource_group.rg.name
    }
    
    # Enables you to manage Private DNS zone Virtual Network Links
    resource "azurerm_private_dns_zone_virtual_network_link" "default" {
      name                  = "mysqlfsVnetZone${random_string.name.result}.com"
      private_dns_zone_name = azurerm_private_dns_zone.default.name
      resource_group_name   = azurerm_resource_group.rg.name
      virtual_network_id    = azurerm_virtual_network.default.id
    }
    
    # Manages the MySQL Flexible Server
    resource "azurerm_mysql_flexible_server" "default" {
      location                     = azurerm_resource_group.rg.location
      name                         = "mysqlfs-${random_string.name.result}"
      resource_group_name          = azurerm_resource_group.rg.name
      administrator_login          = random_string.name.result
      administrator_password       = random_password.password.result
      backup_retention_days        = 7
      delegated_subnet_id          = azurerm_subnet.default.id
      geo_redundant_backup_enabled = false
      private_dns_zone_id          = azurerm_private_dns_zone.default.id
      sku_name                     = "GP_Standard_D2ds_v4"
      version                      = "8.0.21"
      zone                         = "1"
    
      high_availability {
        mode                      = "ZoneRedundant"
        standby_availability_zone = "2"
      }
      maintenance_window {
        day_of_week  = 0
        start_hour   = 8
        start_minute = 0
      }
      storage {
        iops    = 360
        size_gb = 20
      }
    
      depends_on = [azurerm_private_dns_zone_virtual_network_link.default]
    }
    
  4. Create a file named mysql-fs-db.tf and insert the following code:

    # Manages the MySQL Flexible Server Database
    resource "azurerm_mysql_flexible_database" "default" {
      charset             = "utf8"
      collation           = "utf8_unicode_ci"
      name                = "mysqlfsdb_${random_string.name.result}"
      resource_group_name = azurerm_resource_group.rg.name
      server_name         = azurerm_mysql_flexible_server.default.name
    }
    
  5. Create a file named variables.tf and insert the following code:

    variable "resource_group_location" {
      default     = "eastus"
      description = "Location of the resource group."
    }
    
    variable "resource_group_name_prefix" {
      default     = "rg"
      description = "Prefix of the resource group name that's combined with a random ID so name is unique in your Azure subscription."
    }
    
  6. Create a file named outputs.tf and insert the following code:

    output "azurerm_mysql_flexible_server" {
      value = azurerm_mysql_flexible_server.default.name
    }
    
    output "mysql_flexible_server_database_name" {
      value = azurerm_mysql_flexible_database.default.name
    }
    
    output "resource_group_name" {
      value = azurerm_resource_group.rg.name
    }
    

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.
  • To read more about persisting execution plans and security, see the security warning section.

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, call terraform apply without any parameters.

Verify the results

Run az mysql flexible-server db show to display the Azure MySQL database.

az mysql flexible-server db show \
    --resource-group <resource_group_name> \
    --server-name <azurerm_mysql_flexible_server> \
    --database-name <mysql_flexible_server_database_name>

Key points:

  • The values for the <resource_group_name>, <azurerm_mysql_flexible_server>, and <mysql_flexible_server_database_name> are displayed in the terraform apply output. You can also run the terraform output command to view these output values.

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.
    • To read more about persisting execution plans and security, see the security warning section.
  2. Run terraform apply to apply the execution plan.

    terraform apply main.destroy.tfplan
    

Troubleshoot Terraform on Azure

Troubleshoot common problems when using Terraform on Azure

Next steps