EmmaO91
EmmaO91

Reputation: 458

Terraform - Using a config file for referencing backend data

The documentation explains that you can use a config file when setting up your backend. You partially configure the backend as part of your main.tf file and then point it towards a config file inline as part of the terraform init command.

This works okay, but when it comes to accessing data from this backend it seems as though you have to hardcode in the access credentials. I'm wondering essentially if there's any way for me to point the backend to its config file as part of my main.tf file. Something like this:

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

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

If this feature exists I can't find the documentation for it. Am I missing something or is it just not possible right now?

Upvotes: 2

Views: 1564

Answers (1)

phydeauxman
phydeauxman

Reputation: 1712

I am doing exactly what you are asking and I run everything from Cloud Shell. I keep everything in Github repos and then pull the repo down to a folder in my Cloud Shell. Here is how...

First, create a shell script that has the following lines in it:

#!/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"

Second, add the lines below to your main.tf file to read in the data from your backend:

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}"
  }
}

Upvotes: 1

Related Questions