在Terraform的main.tf文件中输入Azure存储账户变量。

huangapple go评论62阅读模式
英文:

Enter Azure storage account variably in Terraform main.tf

问题

如何将Terraform存储帐户作为变量传递给后端?
我收到以下错误:

#main.tf

terraform {
  required_version = ">= 1.3"
  backend "azurerm" {
    resource_group_name  = "rg-tfstate"
    storage_account_name = var.arg5_terraformStorageAccount
    container_name       = "tfstate"
    key                  = "terraform.tfstate"
    
  }
英文:

How do I pass the Terraform storage account for the backend as variable?
I get the following error:

#main.tf

terraform {
  required_version = ">= 1.3"
  backend "azurerm" {
    resource_group_name  = "rg-tfstate"
    storage_account_name = var.arg5_terraformStorageAccount
    container_name       = "tfstate"
    key                  = "terraform.tfstate"
    
  }
#variables.tf

variable "arg5_terraformStorageAccount" {
  type        = string
  description = "terraformStorageAccount (sensitive)"
  sensitive   = true
}
│ Error: Variables not allowed
│ 
│   on main.tf line 7, in terraform:
│    7:     storage_account_name = var.arg5_terraformStorageAccount
│ 
│ Variables may not be used here.

答案1

得分: 1

你不能这样做,因为你不能在 backend 中使用任何变量。你必须硬编码该值,或者开发一种围绕 TF 进行简单查找和替换的包装器。

英文:

You can't do this, as you can't use any variables in backend. You have to hardcode the value, or develop some-kind of wrapper around TF to do simple find-and-search substitution.

答案2

得分: 0

我最终使用了替代方法。
所以我将我的 main.tf 文件重命名为 main.tftemplate。
在那里,我将想要动态定义的变量命名为 STORAGEACCOUNT
在我的 Github Actions 中,我指定了一个名为 AZURE_TF_STORAGE_ACCOUNT 的变量。

然后在运行 Terraform Apply 之前,我运行以下命令:

sed "s/STORAGEACCOUNT/${{  vars.AZURE_TF_STORAGE_ACCOUNT  }}/g" main.tftemplate > main.tf

这将在 main.tftemplate 中用我在 Github Actions 中添加的变量替换 STORAGEACCOUNT,并将其写入 main.tf 文件。

你可以对文件中的任何字符串执行类似操作。

英文:

I ended up using substitution.
So I renamed my main.tf file to main.tftemplate
In there I named the variable that I wanted to define dynamically STORAGEACCOUNT
In my Github Actions I specified a variable called AZURE_TF_STORAGE_ACCOUNT

Then before I run Terraform Apply, I run the following
sed "s/STORAGEACCOUNT/${{ vars.AZURE_TF_STORAGE_ACCOUNT }}/g" main.tftemplate > main.tf
This replaces STORAGEACCOUNT in main.tftemplate with the variable I added to Github Actions and it writes it into the main.tf file.

You can do that with any String inside a file.

huangapple
  • 本文由 发表于 2023年7月3日 16:08:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76602911.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定