Terraform terraform_remote_state 部分配置 [英] Terraform terraform_remote_state Partial Configuration

查看:36
本文介绍了Terraform terraform_remote_state 部分配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的团队严重依赖 Terraform 中的 S3 远程状态.我们在初始化项目时使用 CLI 的 -backend-config 特性来指定 S3 配置,因此我们实际的 terraform 代码如下所示:

My team relies heavily on S3 remote state from within Terraform. We use the -backend-config feature of the CLI to specify the S3 configuration when initializing projects, so our actual terraform code looks like:

terraform {
  backend "s3" {}
}

只要在 CLI 上使用 -backend-config 指定所有 S3 属性,上述方法就可以很好地工作.

The above works great as long as all the S3 attributes are specified on the CLI with -backend-config.

我们希望在配置中的其他位置使用类似的策略来引用这些状态.由于后端的参数是动态的并在 CLI 上指定,因此我们希望这样做.

We would like to use a similar strategy for referencing these states elsewhere in our configurations. Since the parameters for the backend are dynamic and specified on the CLI, we are looking to do the same.

data "terraform_remote_state" "dns" {
  backend = "s3"
  config {
    key = "configurations/production/dns/terraform.tfstate"
  }
}

在上面的例子中,我们省略了必需的 regionbucket 参数,这当然会导致 plan/apply 失败(其中 not a valid地区:).

In the above example, we've omitted the required region and bucket parameters, which of course causes plan/apply to fail (with not a valid region:).

有没有一种方法可以让我们从 CLI 指定远程状态引用的区域和存储桶,而不是对它们进行硬编码?

Is there a method by which we can specify the region and bucket for remote state references from the CLI instead of hard-coding them?

推荐答案

backend 块比较特殊,因为它在 Terraform 的工作流程中很早就被处理了,因此它无法正常访问Terraform 特征,例如变量.这就是为什么它有自己的特殊配置机制.

The backend block is rather special because it gets processed so early in Terraform's workflow, and thus it doesn't have access to normal Terraform features such as variables. That's why it has its own special mechanism for configuring it.

另一方面,terraform_remote_state 数据源只是一个常规数据源,因此可以使用任何常规插值策略.例如,要从 CLI 传递设置,您可以使用变量:

The terraform_remote_state data source, on the other hand, is just a regular data source and so any normal interpolation strategy can be used with it. To pass settings from the CLI, for example, you could use variables:

variable "dns_state_region" {
}

variable "dns_state_key" {
}

data "terraform_remote_state" "dns" {
  backend = "s3"
  config {
    region = "${var.dns_state_region}"
    key    = "${var.dns_state_key}"
  }
}

然后您可以将这些传递给 terraform plan 命令:

You can then pass these to the terraform plan command:

$ terraform plan 
    -var="dns_state_region=us-west-1" 
    -var="dns_state_key=configurations/production/dns/terraform.tfstate"

这篇关于Terraform terraform_remote_state 部分配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆