terraform - 我可以在 TerraForm main.tf 文件中使用变量吗?

标签 terraform terraform-provider-azure

好的,所以我有三个 .tf -文件:main.tf我将 azure 声明为提供者,resources.tf我的所有资源都被认领了,variables.tf .

我用 variables.tf存储 resources.tf 使用的 key .

但是,我想使用存储在我的变量文件中的变量来填充后端范围中的字段,如下所示:
main.tf :

provider "azurerm" {
    version = "=1.5.0"
}

    terraform {
        backend "azurerm" {

        storage_account_name = "${var.sa_name}"
        container_name = "${var.c_name}"
        key = "${var.key}"
        access_key = "${var.access_key}"
    }
}

存储在 variables.tf 中的变量像这样:
variable "sa_name" {
    default = "myStorageAccount"
}

variable "c_name" {
    default = "tfstate"
}

variable "key" {
    default = "codelab.microsoft.tfstate"
}

variable "access_key" {
    default = "weoghwoep489ug40gu ... "
}

我在运行时得到了这个 terraform init :

terraform.backend: configuration cannot contain interpolations

The backend configuration is loaded by Terraform extremely early, before the core of Terraform can be initialized. This is necessary because the backend dictates the behavior of that core. The core is what handles interpolation processing. Because of this, interpolations cannot be used in backend configuration.

If you'd like to parameterize backend configuration, we recommend using partial configuration with the "-backend-config" flag to "terraform init".



有没有办法解决这个问题?我真的希望我的所有 key / secret 都在同一个文件中......而不是主文件中的一个我最好推到 git 的 key 。

最佳答案

Terraform 不太关心文件名:它只是加载所有 .tf当前目录中的文件并处理它们。名称如 main.tf , variables.tf , 和 outputs.tf是使开发人员更容易浏览代码的有用约定,但它们不会对 Terraform 的行为产生太大影响。

您看到错误的原因是您试图在 backend 中使用变量。配置。不幸的是,Terraform 不允许在后端进行任何插值(任何 ${...} )。引自 documentation :

Only one backend may be specified and the configuration may not contain interpolations. Terraform will validate this.



因此,您必须对 backend 中的所有值进行硬编码。 ,或提供 partial configuration并使用外部工具(例如, Terragrunt )通过 CLI 参数填写其余配置。

关于terraform - 我可以在 TerraForm main.tf 文件中使用变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52385397/

相关文章:

azure - 将值从 Terraform 动态加载到 map 中

azure - 如何在 terraform 中循环访问下面给定的变量

node.js - 尽管指定了 Kubernetes 部署/服务端口,但连接端口错误

azure - 如何引用 terraform 中的对象

带有 agic 的 Azure AKS - 如何使用 Terraform 创建它?

azure - 如何使用 Terraform 在 Azure API 管理中导入 Azure Function App?

kubernetes - Kubectl 缺少 Terraform Cloud 形式

azure - 在 Windows 中使用 Azure CLI 命令与 Terraform "data source"失败

amazon-web-services - 为什么CloudFormation在添加资源标签时会替换资源?

Azure 独立应用服务环境无法使用 Terraform 创建,错误代码为 "An error has occurred."