Importing Azure Resource To Terraform State After Timed Out Pipeline

This article will explain how to simply import a resource that was successfully deployed by Terraform from a GitHub action or DevOps pipeline that timed out into your state file.

Background

I’m working a lot with Terraform these days. ARM doesn’t scale, and while I’d prefer to use a native toolset such as Bicep, it is just a prettier ARM and has most of the same issues – scale (big architectures) and support (Azure AD = helloooo!).

The Scenario

You are writing Terraform to deploy resources in Microsoft Azure. That code is run by a DevOps pipeline or a GitHub action. You add a resource such as App Service Environment v3 or Azure SQL Managed Instance that can take hours to deploy. A DevOps pipeline will timeout after 1 hour.

As expected, the pipeline times out but the resource deploys. You try to run the pipeline again but pipeline will fail because you have resources that don’t exist in the state file. Ouch! You do your due diligence and search, and you find nothing but noise, and that does not help you. That was my experience, anyway!

State File Lock

I use blob storage in secured Azure Storage Accounts to store state files. The timed-out pipeline locked the state file using a blob lease. Browse to the container, select the blob and release the lock.

The Fix

The fix is actually pretty simple. You’ve already done most of the work – defining the resource.

In my example, I have a file called ase.tf. I have a resource definition that goes something like this:

resource "azurerm_app_service_environment_v3" "ase" {

...

}

I made a copy of my pipeline file. Then I modified my pipeline yaml file so it would run a terraform import command instead of a terraform apply.

terraform import azurerm_app_service_environment_v3.ase /subscriptions/<subscription id>/resourceGroups/<resource group name>/providers/Microsoft.Web/hostingEnvironments<resource name>

I used the  GetAzAppServiceEnvironment cmdlet in Cloud Shell to retrieve the resource ID of the ASE because it wasn’t shared in the Azure Portal.

I re-ran the pipeline and the state file was updated with the resource. Reset the pipeline file back to the way it was (back to terraform apply) and your pipeline should run clean.

One thought on “Importing Azure Resource To Terraform State After Timed Out Pipeline”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.