Intro

In this post we will cover how to import an existing Azure SQL Database to Terraform. If the resource wasn’t originally created by Terraform you will need to import it before Terraform can manage it. This comes in handy when you have existing infrastructure and want to start using Terraform later on.

For a video walkthrough check out my YouTube video.

Here we will use the standard import functionality provided by Terraform. There are other 3rd party tools you can use for this process as well. One of the most popular is Terraformer, I will cover how to use that in a later post.

Prerequisites

In a previous post on creating an Azure SQL Database, we deployed a Resource Group, SQL Server, and SQL Database. Today we will create a new project and import those existing resources so we can manage them with Terraform.

The import command will not reverse engineer your cloud infrastructure to Terraform for you. What the import command does is generate the state file for you. If you start with Terraform and deploy infrastructure, a state file is maintained along the way. When you start using Terraform after you already have infrastructure, you need to import it so Terraform can manage it.

Define Resources

We need to create our main.tf file same as we did in the previous post. This is just like creating any normal Terraform from scratch. Code for this file can be found in my GitHub repo.

Import Resources

Now to import the Azure resources into the Terraform state file. In the first part of the import command we define a resource type and its name. We can pull this directly from our resource in the Terraform code. The second part we can copy and paste from the URL of our Azure resource. Simply navigate to the resource in the Azure portal and you should see the pattern in the URL.

First up is the resource group.

Here is the resource group in the main.tf file. We need the resource type and name.

Here is the resource group in the Azure Portal. We need to copy everything from subscriptions to the last forward slash.

Using the info from both we create the import command to run.

Resource Group

terraform import "azurerm_resource_group.rg-terraform" "/subscriptions/xxxxxxxxxxxxx/resourceGroups/rg-terraform"

SQL Server

terraform import "azurerm_mssql_server.sql-server-terraform" "/subscriptions/xxxxxxxxxxxxx/resourceGroups/rg-terraform/providers/Microsoft.Sql/servers/sql-server-terraform"

SQL Database

terraform import "azurerm_mssql_database.db-terraform" "/subscriptions/xxxxxxxxxxxxx/resourceGroups/rg-terraform/providers/Microsoft.Sql/servers/sql-server-terraform/databases/db-terraform"

Wrapping Up

Now that we have imported our resources we need to test to make sure Terraform sees everything and doesn’t want to make any changes.

  1. Run terraform plan
  2. The result should be no changes

You have successfully imported your Azure SQL Database to Terraform.