我知道为了在我的terraform代码中有一个远程状态,我必须创建一个存储帐户和一个容器。通常,这是手动完成的,但我试图使用以下代码动态创建存储帐户和容器:
resource "azurerm_resource_group" "state_resource_group" {
name = "RG-Terraform-on-Azure"
location = "West Europe"
}
terraform {
backend "azurerm" {
resource_group_name = "RG-Terraform-on-Azure"
storage_account_name = azurerm_storage_account.state_storage_account.name
container_name = azurerm_storage_container.state_container.name
key = "terraform.tfstate"
}
}
resource "azurerm_storage_account" "state_storage_account" {
name = random_string.storage_account_name.result
resource_group_name = azurerm_resource_group.state_resource_group.name
location = azurerm_resource_group.state_resource_group.location
account_tier = "Standard"
account_replication_type = "LRS"
tags = {
environment = "staging"
}
}
resource "azurerm_storage_container" "state_container" {
name = "vhds"
storage_account_name = azurerm_storage_account.state_storage_account.name
container_access_type = "private"
}
resource "random_string" "storage_account_name" {
length = 14
lower = true
numeric = false
upper = false
special = false
}但是,上述代码抱怨说:
│ Error: Variables not allowed
│
│ on main.tf line 11, in terraform:
│ 11: storage_account_name = azurerm_storage_account.state_storage_account.name
│
│ Variables may not be used here.因此,我已经知道我不能在后端block中使用变量,但是我想知道是否有一种解决方案,使我能够动态地创建存储帐户和容器,并将状态文件存储在其中?
要点:我已经看过this question,了,但是.conf文件对我不起作用!
发布于 2022-08-28 14:59:05
这不能在同一个Terraform文件中完成。后端必须比其他任何东西都先存在。Terraform在运行terraform init时要求后端存在。在实际创建任何资源之前,将访问后端来读取状态,就像执行plan或apply时Terraform执行的第一步操作一样。
在过去,我使用CLI工具自动创建存储后端。如果您想要用terraform实现它的自动化,那么它必须在一个单独的Terraform工作区中,但是该工作区的后端在哪里呢?
通常,在Terraform中创建后端并不有效。
https://stackoverflow.com/questions/73518974
复制相似问题