Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mnhat3896/49c2b21fa2aae0b66cfa62f4761b95d6 to your computer and use it in GitHub Desktop.
Save mnhat3896/49c2b21fa2aae0b66cfa62f4761b95d6 to your computer and use it in GitHub Desktop.
Initializing Terraform Backend

When initalizing a Terraform backend, a .terraform/terraform.tfstate file is written to disk and can include storage account secrets.

Option 1

Include the Azure Storage key in the Terraform configuration.

Not ideal: the Storage access key is exposed both in the configuration and in the .terraform/terraform.tfstate file.

Configuration:

terraform {
  backend "azurerm" {
    storage_account_name = "tstate"
    container_name       = "tstate"
    key                  = "terraform.tfstate"
    access_key           = "<azure-storage-account-key>"
  }
}

Init command:

terraform init

terraform.tfstate file, key is visible.

"backend": {
    "type": "azurerm",
    "config": {
        "access_key": "<azure-storage-account-key>",
        "container_name": "tstate",
        "key": "terraform.tfstate",
        "storage_account_name": "tstate"
    },
    "hash": 13235237982197025795
},

Option 2

Use partial configuration and pass the Azure Storage key as a parameter to terraform init.

Not ideal: The storage access key is still written to the .terraform/terraform.tfstate file.

Configuration:

terraform {
  backend "azurerm" {
    storage_account_name = "tstate"
    container_name       = "tstate"
    key                  = "terraform.tfstate"
  }
}

Init command:

terraform init -backend-config="access_key=<azure-storage-account-key>"

terraform.tfstate file, key is visible.

"backend": {
    "type": "azurerm",
    "config": {
        "access_key": "<azure-storage-account-key>",
        "container_name": "tstate",
        "key": "terraform.tfstate",
        "storage_account_name": "tstate"
    },
    "hash": 13235237982197025795
},

Option 3

Use partial configuration and put the Azure Storage access key in an environment variable named ARM_ACCESS_KEY.

Most ideal: The storage access key is not written to the .terraform/terraform.tfstate file.

Configuration:

terraform {
  backend "azurerm" {
    storage_account_name = "tstate"
    container_name       = "tstate"
    key                  = "terraform.tfstate"
  }
}

Furthermore, keep the access key out of terminal history with Azure Key Vault.

ARM_ACCESS_KEY=$(az keyvault secret show --name tstate-key --vault-name billBooth --query value -o tsv)

Init command:

terraform init

terraform.tfstate file, key is not visible.

"backend": {
    "type": "azurerm",
    "config": {
        "container_name": "tstate",
        "key": "terraform.tfstate",
        "storage_account_name": "tstate"
    },
    "hash": 3693603136239683338
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment