首页 > 解决方案 > 需要后端初始化,请运行“terraform init”

问题描述

我的后端有以下 Terraform 配置,它工作了一段时间,

terraform {
  required_providers {
    azurerm = {
      source = "hashicorp/azurerm"
    }
  }

  backend "azurerm" {
    resource_group_name  = "my-rg"
    storage_account_name = "my-sa"
    ####!!!!! BELOW USED TO WORK !!!!###
    provider             = azurerm.mysub  
    key                  = "terraform.tfstate"
  }
}

provider "azurerm" {
  skip_provider_registration = true
  subscription_id            = "xxxxxx-xxxxx-xxxxx-xxxxx"  
  alias                      = "mysub"
  features {
  }
}

然而,升级后它说这个块中不允许提供者(我不记得确切的错误消息)。所以相反我改变了它,

terraform {
  required_providers {
    azurerm = {
      source = "hashicorp/azurerm"
    }
  }

  backend "azurerm" {
    resource_group_name  = "my-rg"
    storage_account_name = "my-sa"
    ###!!!! Direct Reference to Subscription ID !!!!###
    subscription_id      = "xxxxxx-xxxxx-xxxxx-xxxxx"  
    key                  = "terraform.tfstate"
  }
}

然而现在它说,

│ Error: Backend initialization required, please run "terraform init"
│
│ Reason: Backend configuration changed for "azurerm"
│
│ The "backend" is the interface that Terraform uses to store state,
│ perform operations, etc. If this message is showing up, it means that the
│ Terraform configuration you're using is using a custom configuration for
│ the Terraform backend.
│
│ Changes to backend configurations require reinitialization. This allows
│ Terraform to set up the new configuration, copy existing state, etc. Please run
│ "terraform init" with either the "-reconfigure" or "-migrate-state" flags to
│ use the current configuration.
│
│ If the change reason above is incorrect, please verify your configuration
│ hasn't changed and try again. At this point, no changes to your existing
│ configuration or state have been made.

如果我想让它记住状态以便以后知道如何销毁它,我应该使用什么命令?我已经使用 terraform 在这个 RG 中部署了几次资源迭代,并希望保持原样。

terraform 初始化,或,

terraform init -reconfigure,或者,

terraform init -migrate-state ??

由于后端位置没有改变,我想按原样继续,但只是让它忽略从使用“提供者”到使用“订阅 ID”的后端块更新。我使用哪个命令?

提前致谢!

标签: azureterraform

解决方案


terraform init文档对这种情况进行了以下说明:

使用已经初始化的后端重新运行 init 将更新工作目录以使用新的后端设置。必须提供-reconfigure-migrate-state以更新后端配置。

-migrate-state选项将尝试将现有状态复制到新后端,并且根据更改的内容,可能会导致交互式提示确认工作空间状态的迁移。该-force-copy选项会抑制这些提示并对迁移问题回答“是”。这意味着-migrate-state

-reconfigure选项忽略任何现有配置,防止迁移任何现有状态。

这里的决定点是您是否希望 Terraform 采取显式操作以尝试将状态复制到新位置 ( -migrate-state),或者您是否希望 Terraform 完全忘记旧设置并直接使用新设置。

你说物理位置没有改变,相反你只是用不同的方式写了相同的信息-reconfigure,与这种情况相匹配的选项也是如此:这里不需要任何显式迁移,因为状态已经在“新" 位置(在功能上与旧位置相同,但 Terraform 不知道)。


请注意,将后端配置与提供程序相关联从来都不是有效的,因此您之前所做的任何工作都不会以您认为的方式工作。

如果您没有在其配置中明确设置,后端具有查找环境变量的azurerm行为,所以我猜您之前在设置了该环境变量的上下文中运行 Terraform,因此后端能够找到即使您没有明确设置它,也要使用适当的订阅 ID。ARM_SUBSCRIPTION_IDsubscription_id

provider我不清楚为什么后端没有拒绝无效的论点。这表明 Terraform 或后端本身存在错误,该错误已得到修复,因此 Terraform 现在正确报告provider该后端的配置模式中没有声明任何参数。


推荐阅读