【发布时间】:2018-07-28 13:57:20
【问题描述】:
我正在尝试通过 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] 被抛出。
【问题讨论】:
-
抱歉,有什么不工作?有什么错误吗?
-
我不确定这是否是一个简化的示例,但您仍然需要定义您在
variable "var_name" {}样式中使用的变量。 -
@ChandanNayak 我无法执行 terraform 命令行,我在其中传入变量并同时使用变量文件。
-
@ydaetskcoR 我忘了定义你提到的变量,但它似乎没有改变任何东西。我编辑了原始帖子以反映我如何尝试添加声明和结果。
-
看起来您的 access_key 将值作为映射而不是字符串获取,您的 "echo $tfstate_storage_access_key" 打印什么?
标签: azure terraform terraform-provider-azure terraform-template-file