我正在尝试通过 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]
被抛出。