Terraform - 使用配置文件来引用后端数据

时间:2018-02-14 09:29:41

标签: terraform

文档说明您可以在设置后端时使用配置文件。您将后端部分配置为main.tf文件的一部分,然后将其指向内联配置文件,作为terraform init命令的一部分。

这没关系,但是当涉及从这个后端访问数据时,似乎你必须在访问凭证中进行硬编码。我基本上想知道是否有任何方法让我将后端指向其配置文件作为main.tf文件的一部分。像这样:

data "terraform_remote_state" "vnet"
{
    backend = "azurerm"

    config {
        key = "path/to/state/file"
        file = "path/to/config/file.tf"
    }
}

如果此功能存在,我无法找到相应的文档。我错过了什么或现在不可能吗?

1 个答案:

答案 0 :(得分:1)

我正在按照您的要求行事,我从Cloud Shell运行所有内容。我将所有内容保存在Github repos中,然后将repo下拉到我的Cloud Shell中的一个文件夹中。这是如何......

首先,创建一个shell脚本,其中包含以下行:

#!/bin/bash
set -eo pipefail

# The block below will grab the access key for the storage account that is used
# to store state files

subscription_name="Infrastructure"
tfstate_storage_resource_group="terraform-state-rg"
tfstate_storage_account="dosinvesttfstatesa"

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 ""
echo "Terraform state storage account access key:"
echo $tfstate_storage_access_key
echo ""

terraform apply \
  -var "tfstate_access_key=$tfstate_storage_access_key"

其次,将以下行添加到main.tf文件中以读取后端数据:

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

  config {
    storage_account_name = "${var.tfstate_storage_account}"
    container_name       = "${var.tfstate_container}"
    key                  = "${var.tfstate_rgstate_file}"
    access_key           = "${var.tfstate_access_key}"
  }
}