我正在尝试通过Shell脚本运行Terraform部署,在Shell脚本中,我首先动态收集Azure存储帐户的访问密钥并将其分配给变量。然后,我想在terraform命令行的-var赋值中使用该变量。在为远程状态配置后端时,此方法很有效,但它不能用于执行部署。模板中使用的其他变量是从terraform.tfvars文件中提取的。下面是我的Shell脚本和Terraform模板:
Shell脚本:
#!/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]
被抛出。
答案 0 :(得分:0)
玩了几个小时之后...我几乎感到尴尬的是问题是什么但是我也对Terraform感到沮丧,因为我浪费了这个问题。
我在variables.tf
文件中定义了所有变量,除了一个具有默认值之外的所有变量。对于没有默认值的那个,我将它作为命令行的一部分传递。我的命令行是问题所在。由于我阅读的所有文档,我认为我必须使用-var-file
选项告诉terraform我的变量文件是什么。事实证明你没有,当我这样做时抛出了错误。事实证明我所要做的就是对没有定义默认值的变量使用-var
选项,而terraform只是自动查看variables.tf
文件。令人沮丧。我爱上了Terraform,但我会给予它的一个否定就是文档缺乏。