Home > Enterprise >  Terraform can't create resource in group already exist
Terraform can't create resource in group already exist

Time:11-29

I would create a sample azure web app using Terraform. I use this code to create the resoucre.

This is my main.tf file :

resource "azurerm_resource_group" "rg" {
  name     = var.rgname
  location = var.rglocation
}

resource "azurerm_app_service_plan" "plan" {
  name                = var.webapp_plan_name
  location            = var.rglocation
  resource_group_name = var.rgname
  sku {
    tier     = var.plan_settings["tier"]
    size     = var.plan_settings["size"]
    capacity = var.plan_settings["capacity"]
  }
}

resource "azurerm_app_service" "webapp" {
  name                = var.webapp_name
  location            = var.rglocation
  resource_group_name = var.rgname
  app_service_plan_id = azurerm_app_service_plan.plan.id
}

and this is the variable.tf

# variables for Resource Group
variable "rgname" {
  description = "(Required)Name of the Resource Group"
  type        = string
  default     = "example-rg"
}

variable "rglocation" {
  description = "Resource Group location like West Europe etc."
  type        = string
  default     = "eastus2"
}

# variables for web app plan
variable "webapp_plan_name" {
  description = "Name of webapp"
  type        = string
  default     = "XXXXXXXXXx"
}

variable "plan_settings" {
  type        = map(string)
  description = "Definition of the dedicated plan to use"

  default = {
    kind     = "Linux"
    size     = "S1"
    capacity = 1
    tier     = "Standard"
  }
}

variable "webapp_name" {
  description = "Name of webapp"
  type        = string
  default     = "XXXXXXXX"
}

The terraform apply --auto-approve show a error :

Error: creating/updating App Service Plan "XXXXXXXXXXX" (Resource Group "example-rg"): web.AppServicePlansClient#CreateOrUpdate: Failure sending request: StatusCode=0 -- Original Error: Code="ResourceGroupNotFound" Message="Resource group 'example-rg' could not be found." 

but in Azure Portal , the ressource group is created

what's wrong in my code ?

Can i hold on Terraform to check if resource is created or not before pass to next resource ?

CodePudding user response:

You need to reference the resources to indicate the dependency between them to terraform, so that it can guarantee, that the resource group is created first, and then the other resources. The error indicates, that the resource group does not exist, yet. Your code tries to create the ASP first and then the RG.

resource "azurerm_resource_group" "rg" {
  name     = var.rgname
  location = var.rglocation
}

resource "azurerm_app_service_plan" "plan" {
...
  resource_group_name = azurerm_resource_group.rg.name
...
}
  • Related