首页 > 解决方案 > terraform 中的状态管理

问题描述

我正在构建 terraform 脚本来 orcastrate Azure 部署。我使用 Azure Blob 存储来存储tfstate文件。此文件与多个管道 IAC 管道共享。

例如,如果我使用 terraform 创建了一个 Azure 资源组,完成后,我会尝试创建一个新的自定义角色,terraform 计划会将资源组标记为销毁。

这是创建角色的脚本:

terraform {
  backend "azurerm" {
    storage_account_name = "saiac"
    container_name       = "tfstate"
    key                  = "dev.terraform.tfstate"
    resource_group_name  = "rg-devops"
  }
}

data "azurerm_subscription" "primary" {
}

resource "azurerm_role_definition" "roles" {
  count              = length(var.roles)
  name               = "${var.role_prefix}${var.roles[count.index]["suffix_name"]}${var.role_suffix}"
  scope              = "${data.azurerm_subscription.primary.id}"

  permissions {
    actions = split(",", var.roles[count.index]["actions"])

    not_actions = split(",", var.roles[count.index]["not_actions"])
  }

  assignable_scopes = ["${data.azurerm_subscription.primary.id}"]
}

这是创建资源组的脚本:

terraform {
  backend "azurerm" {
    storage_account_name = "saiac"
    container_name       = "tfstate"
    key                  = "dev.terraform.tfstate"
    resource_group_name  = "rg-devops"
  }
}

resource "azurerm_resource_group" "rg" {
  count         = "${length(var.rg_purposes)}"
  name          = "${var.rg_prefix}-${var.rg_postfix}-${var.rg_purposes[count.index]}"
  location      = "${var.rg_location}"
  tags          = "${var.rg_tags}" 
}

如果我删除后端块,一切都按预期工作,这是否意味着我需要后端块?

标签: azureterraform

解决方案


terraform 不需要 terraform 后端。如果您不使用它,那么其他人将无法提取您的代码并运行您的 terraform。状态将仅存储在您的.terraform目录中。这意味着如果您丢失了本地文件,您将遇到麻烦。建议使用同样支持azurerm 所做的状态锁定的后端。有了后端,在拉取 repo 后,状态将被拉到terraform init上。


推荐阅读