Azure DevOps and .tfstate

Hi,
Just starting out with Terraform, been using ARM templates for years and have a couple of questions.

I have all my terraform runbooks in DevOps, so I can version/track changes. If I pull down the latest branch, make a change to the plan and execute, the operation generates the .tfstate file. This file contains sensitive information that I wouldn’t want to store in source control, but I want to be able to maintain the state of a previous run. How do people manage this and how do people manage run history when executing terraform from Azure DevOps?

Thanks

Hi TommyQuality,

I am not using Azure DevOps at the moment, but, this should at least point you in the right direction.

In main.tf I use what is called a “partial configuration” in the terraform block, like this:

# Configure Azurerm provider
provider “azurerm” {
subscription_id = var.subscription_id
tenant_id = var.tenant_id
client_id = var.client_id
client_secret = var.client_secret
}

terraform {
backend “azurerm” {}
}

And in my Jenkinsfile one of the build steps includes the following:

sh ‘’’
echo '[INFO] Logging into Azure with SPN'
az login --service-principal -u ${TF_VAR_client_id} -p ${TF_VAR_client_secret} -t ${TF_VAR_tenant_id}
terraform init -upgrade -input=false \
-backend-config="storage_account_name=${TF_VAR_storage_account_name}" \
-backend-config="container_name=${TF_VAR_container_name}" \
-backend-config="key=${TF_VAR_key}" \
-backend-config="access_key=${TF_VAR_access_key}"
‘’’

The “-backend-config=” directives complete the terraform block “partial configuration”. The login using a service principal essentially gives my build container access to Azure storage for remote-state purposes. Personally, I like to store state using regions/environment/component so that if someone messes up, say. with resources in west-us-2/dev/vm they won’t take down all the other dev resources like vpc…

There are many opinions on how to organize your code and remote-state. A couple of helpful places to begin might be: