首页 > 解决方案 > 只有通过 terraform 添加资源会导致首先销毁它

问题描述

我有 2 个 terraform 配置文件,例如db.tfapp.tf用于 Azure 云中的资源配置

db.tf用于数据库,app.tf用于 Web 应用程序。

两个 terraform 文件只将相应的资源添加到同一个资源组中。但是app.tf提供将首先破坏db.tf创建的所有资源,反之亦然。

如果我只想更改或向数据库添加更多资源,那么它会破坏并重新创建我的应用程序文件,这很烦人

PS: db.tfapp.tf有自己的状态文件

问题:我必须做一项规定,共同负责所有资源吗?

以下代码片段是 db.tf 的抽象版本,与app.tf不同的部分由注释标记

#Some Azure resources require a globally unique ID, the random provider is used to generate a unique suffix
provider "random" {
  version = "= 2.3.0"
}

# We use an Azure remote backend to store the Terraform state
terraform {
  required_providers {
    azure = {
      source = "hashicorp/azurerm"
      version = "~>1.32.0"
    }
  }

  # for db.tf the container_name is abcdefinfratfstate
  # for app.tf the container_name is abcdefapptfstate
  backend "azurerm" {
    resource_group_name   = "RG-terraform-state"
    storage_account_name  = "abcdefinfratfstate" //This will be called abcdefapptfstate for app.tf
    container_name        =  "dev-tfstate"
    key                   = "terraform.tfstate"
  }
}


# resource group for Dev deployment, both db.tf and app.tf are the same
resource "azurerm_resource_group" "rg" {
  name     = "RG-abcdef-Dev"
  location = "westeurope"
}

# Generate a random ID that is tied to the environment name
resource "random_id" "rid" {
  byte_length = 4
}

variable "project_prefix" {
  type        = string
  description = "The name of the storage account. This must be globally unique, not just within the resource group."
  default     = "abcdef"
}

variable "deploy_env_prefix" {
  type        = string
  description = "the deployment environment"
  default     = "dev"
}

# container registry for abcdef-api docker image, for app.tf there will be different resources
module "infra_container_registry" {
  source                  = "../../modules/infra/container_registry" //I have a module file to configure the container registry resource
  resource_group          = azurerm_resource_group.rg
  container_registry_name = "dev${var.project_prefix}Acr${random_id.rid.hex}"
}

标签: azureterraformterraform-provider-azure

解决方案


推荐阅读