首页 > 解决方案 > 如何在 terraform 中实现“粘性”变量?

问题描述

我想要一个具有以下属性的 Terraform 变量:

该用例适用于 AWS ECS 标签,我希望能够通过更改标签来部署新版本,这将导致 Terraform 创建新的任务定义并修改服务定义。但是,如果我运行“terraform apply”,但不传递新值,我不希望发生任何事情,即 terraform 会记住上一次运行的值。

欢迎提出建议!

标签: terraformamazon-ecs

解决方案


我试图做类似的事情并遇到了这篇文章。最后制定了一个解决方案,所以我想我应该分享给其他遇到这篇文章的人。

variable "maintenance" {
  description = "Set to active, disabled or previous (Default)"
  type        = string
  default     = "previous"
}

# This is used so we can lookup the previous value of the maintenance setting in the state file
data "terraform_remote_state" "bc" {
  backend = "gcs"

  config = {
    bucket = "terraform-bucket"
    prefix = "terraform/state"
  }

  workspace = terraform.workspace

  # Set a default value in case of an empty state file
  defaults = {
    maintenance = "disabled"
  }
}

locals {
  maintenance_status = var.maintenance == "previous" ? data.terraform_remote_state.bc.outputs.maintenance : var.maintenance
}

# Used to expose the current value to subsequent tf runs
output "maintenance" {
  value = example_resource.maintenance.status
}

然后您可以使用命令行更改设置,但如果未指定,它将使用以前的值 terraform apply -var="maintenance=active"


推荐阅读