在创建另一个之前删除后端池和负载均衡器规则

Removing Backend pools and load balancer rules before creating another

我有 terraform 脚本,它在资源组的 Loadbalancer 中创建后端地址池和 Loadbalancer 规则。这些任务包含在 Azure 管道中。我第一次 运行 pipeline.Its 正确创建。如果我运行管道第二次。它没有更新现有的。它保留了前一版本创建的后端地址池和负载均衡器规则,并为此版本添加了额外的后端地址池和负载均衡器规则,这导致后端地址池和负载均衡器规则重复。对此有任何建议

resource "azurerm_lb_backend_address_pool" "example" {
  resource_group_name = azurerm_resource_group.example.name
  loadbalancer_id     = azurerm_lb.example.id
  name                = "BackEndAddressPool"
}

resource "azurerm_lb_rule" "example" {
  resource_group_name            = azurerm_resource_group.example.name
  loadbalancer_id                = azurerm_lb.example.id
  name                           = "LBRule"
  protocol                       = "All"
  frontend_port                  = 0
  backend_port                   = 0
  frontend_ip_configuration_name = "PublicIPAddress"
  enable_floating_ip             = true
  backend_address_pool_id        = azurerm_lb_backend_address_pool.example
}

这很可能发生,因为 Terraform 状态文件在管道运行之间丢失。

By default, Terraform stores state locally in a file named terraform.tfstate. When working with Terraform in a team, use of a local file makes Terraform usage complicated because each user must make sure they always have the latest state data before running Terraform and make sure that nobody else runs Terraform at the same time. With remote state, Terraform writes the state data to a remote data store, which can then be shared between all members of a team. Terraform supports storing state in Terraform Cloud, HashiCorp Consul, Amazon S3, Alibaba Cloud OSS, and more.

Remote state is a feature of backends. Configuring and using remote backends is easy and you can get started with remote state quickly. If you then want to migrate back to using local state, backends make that easy as well.

您需要配置 Remote State storage 以保持状态。以下是使用 Azure Blob 存储的示例:

terraform {
  backend "azurerm" {
    resource_group_name  = "StorageAccount-ResourceGroup"
    storage_account_name = "abcd1234"
    container_name       = "tfstate"
    key                  = "prod.terraform.tfstate"
  }
}

Stores the state as a Blob with the given Key within the Blob Container within the Blob Storage Account. This backend also supports state locking and consistency checking via native capabilities of Azure Blob Storage.

这在 azurerm Terraform backend docs 中有更完整的描述。

Microsoft 还提供了一个 Tutorial: Store Terraform state in Azure Storage,它会逐步完成设置。