How to use the terraform state in another azure subscription

951 views Asked by At

I am deploying an azure infrastructure with Terraform. The terraform state will be stored in a subscription which will be different from the main deployment subscription. I am using alias in provider declaration. My terraform code is like below:

terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "~> 2.38.0"
    }
  }
  backend "azurerm" {
    resource_group_name  = "resourcegroup_name"  
    storage_account_name = "storageaccount_name" 
    container_name       = "mystate"
    key                  = "tfstatename1.tfstate"
  }
}

provider "azurerm" {
  features {}
}

provider "azurerm" {
  features {}
  alias = "second_subscription"  
  subscription_id = var.second_subscription_id
}

My terraform state should be stored in the subscription with alias.

How can i achieve that?

1

There are 1 answers

0
Carl in 't Veld On

I don't think the azurerm backend configuration is taking input from the azurerm provider configuration. To some extent you could say it applies its own authentication mechanism. But there are some features they share nevertheless: e.g. both are capable of using the Azure CLI security context.

In order to explicitly target a subscription id for your backend configuration, you must add it to the backend configuration block. Like so:

backend "azurerm" {
    resource_group_name  = "resourcegroup_name"  
    storage_account_name = "storageaccount_name" 
    container_name       = "mystate"
    key                  = "tfstatename1.tfstate"
    subscription_id      = "091f1800-0de3-4fef-831a-003a74ce245f"
}

Reference: https://developer.hashicorp.com/terraform/language/settings/backends/azurerm