1

我正在尝试通过 Shell 脚本运行 Terraform 部署,在 Shell 脚本中,我首先动态收集 Azure 存储帐户的访问密钥并将其分配给变量。然后我想在 terraform 命令行上的 -var 赋值中使用该变量。此方法在为远程状态配置后端时效果很好,但不适用于进行部署。模板中使用的其他变量是从 terraform.tfvars 文件中提取的。下面是我的 Shell 脚本和 Terraform 模板:

外壳脚本:

#!/bin/bash
set -eo pipefail

subscription_name="Visual Studio Enterprise with MSDN"
tfstate_storage_resource_group="terraform-state-rg"
tfstate_storage_account="terraformtfstatesa"

az account set --subscription "$subscription_name"
tfstate_storage_access_key=$(
  az storage account keys list \
  --resource-group "$tfstate_storage_resource_group" \
  --account-name "$tfstate_storage_account" \
  --query '[0].value' -o tsv
)

echo $tfstate_storage_access_key

terraform apply \
  -var "access_key=$tfstate_storage_access_key"

部署模板:

provider "azurerm" {
  subscription_id = "${var.sub_id}"
}

data "terraform_remote_state" "rg" {
  backend = "azurerm"

  config {
    storage_account_name = "terraformtfstatesa"
    container_name       = "terraform-state"
    key                  = "rg.stage.project.terraform.tfstate"
    access_key           = "${var.access_key}"
  }
}

resource "azurerm_storage_account" "my_table" {
  name                     = "${var.storage_account}"
  resource_group_name      = "${data.terraform_remote_state.rg.rgname}"
  location                 = "${var.region}"
  account_tier             = "Standard"
  account_replication_type = "LRS"
}

我尝试在 terraform.tfvars 文件中定义变量:

storage_account = "appastagesa"

les_table_name = "appatable

region = "eastus"

sub_id = "abc12345-099c-1234-1234-998899889988"

access_key = ""

access_key 定义似乎被忽略了。

然后我尝试不使用terraform.tfvars文件,并在下面创建了 variables.tf 文件:

variable storage_account {
  description = "Name of the storage account to create"
  default     = "appastagesa"
}

variable les_table_name {
  description = "Name of the App table to create"
  default     = "appatable"
}

variable region {
  description = "The region where resources will be deployed (ex. eastus, eastus2, etc.)"
  default     = "eastus"
}

variable sub_id {
  description = "The ID of the subscription to deploy into"
  default     = "abc12345-099c-1234-1234-998899889988"
}

variable access_key {}

然后我修改了我的deploy.sh脚本以使用下面的行来运行我的 terraform 部署:

terraform apply \
  -var "access_key=$tfstate_storage_access_key" \
  -var-file="variables.tf"

这导致错误invalid value "variables.tf" for flag -var-file: multiple map declarations not supported for variables Usage: terraform apply [options] [DIR-OR-PLAN]被抛出。

4

1 回答 1

1

在玩了几个小时之后......我几乎对问题所在感到尴尬,但我也对 Terraform 感到沮丧,因为我在这个问题上浪费了时间。

我在我的variables.tf文件中定义了所有变量,但只有一个变量具有默认值。对于没有默认值的那个,我将它作为命令行的一部分传入。我的命令行是问题所在。-var-file由于我阅读了所有文档,我认为我必须通过使用该选项告诉 terraform 我的变量文件是什么。结果你没有,当我这样做时,它抛出了错误。事实证明,我所要做的就是使用-var没有定义默认值的变量的选项,而 terraform 只是自动看到了variables.tf文件。令人沮丧。我爱上了 Terraform,但我要给它的一个负面因素是缺少文档。

于 2018-02-18T17:39:35.513 回答