Felipe
Felipe

Reputation: 47

Recreating previously deleted AKS with Terraform

I have a resource group on Azure which contains several resources that were originally created with a Terraform script. Somehow I deleted the Kubernetes cluster resource and also reset the TF state. My intention was recreating this AKS module, but now when I run the terraform script pipeline I get the error that the resource already exists for the following resources:

module.keyvault.azurerm_key_vault_access_policy.service_principle_policy: Creating... module.keyvault.azurerm_key_vault_access_policy.users_policy: Creating... module.keyvault.azurerm_key_vault_access_policy.readers_policy: Creating... module.rg.azurerm_resource_group.rg: Creating... module.keyvault.azurerm_key_vault_access_policy.readers_policy: Creating...

My question is, how could I recreate the AKS cluster while keeping the current resources?

Thanks in advance.

Upvotes: 0

Views: 271

Answers (1)

SiddheshDesai
SiddheshDesai

Reputation: 8195

As you have deleted the resources from state file, one possible way is to import the same resource via terraform import command like below:-

terraform import module.keyvault.azurerm_key_vault_access_policy.service_principle_policy <existing_key_vault_id>/accesspolicies/<policy_id>
terraform import module.keyvault.azurerm_key_vault_access_policy.users_policy <existing_key_vault_id>/accesspolicies/<policy_id>
terraform import module.keyvault.azurerm_key_vault_access_policy.readers_policy <existing_key_vault_id>/accesspolicies/<policy_id>
terraform import module.rg.azurerm_resource_group.rg /subscriptions/<subscription_id>/resourceGroups/<resource_group_name>

Another way is to get the terraform configuration of your existing state file and then add terraform configuration code blocks to match the existing state.

Check existing state like below:-

terraform state list

enter image description here

Run terraform show command to check the existing configuration and add the code block of AKS that matches this configuration state.

terraform show

enter image description here

After creating a configuration code for missing or already existing resources like I created one configuration block for NetWorkWatcherRG in my code and imported it in my tfstate :-

enter image description here

Added the configuration block:-

resource "azurerm_resource_group" "NetworkWatcherRG" {
    name = "NetworkWatcherRG"
    location = var.resource_group_location
  
}

enter image description here

Reference:-

Quickstart: Create an Azure Kubernetes Service (AKS) cluster by using Terraform - Azure Kubernetes Service | Microsoft Learn

Upvotes: 1

Related Questions