Problem description -
We have 2 provider configuration defined in the same script and want to execute a data block with particular provider based on the ‘count’ conditional expression. While the data block behaves normally when only the ‘count’ argument is used, when an additional argument of provider is added, it tries to read the provider configuration even if the condition turns out to be false. Question here is, if the condition is false, why the data block needs to execute the provider block?
Terraform config files -
terraform {
required_providers {
azurerm = {
source = “hashicorp/azurerm”
version = “>=3.0.0”
}
}
}
provider “azurerm” {
subscription_id = xxxxx
tenant_id = xxxxx
client_id = xxxxx
client_secret = xxxxx
features {}
}
provider “azurerm” {
alias = “china”
subscription_id = xxxxx
tenant_id = xxxxx
client_id = xxxxx
client_secret = xxxxx
environment = “china”
features {}
}
/* Using Data Source for fetching resource group details */
data “azurerm_resource_group” “rg” {
count = local.tenant == “SHS” ? 1 : 0
name = split("/", var.resource_id)[4]
}
data “azurerm_resource_group” “rg_china” {
count = local.tenant == “china” ? 1 : 0
provider = azurerm.china
name = split("/", var.resource_id)[4]
}
Note: local.tenant variable gets resolved to “SHS” here.
Debug Output
terraform apply --auto-approve
│ Error: building account: getting authenticated object ID: listing Service Principals: ServicePrincipalsClient.BaseClient.Get(): clientCredentialsToken: received HTTP status 400 with response: {“error”:“invalid_request”,“error_description”:“AADSTS90002: Tenant ‘xxxxx-xxxxx-xxxxx-xxxxx-xxxxx’ not found. Check to make sure you have the correct tenant ID and are signing into the correct cloud. Check with your subscription administrator, this may happen if there are no active subscriptions for the tenant.\r\nTrace ID: e36ac19c-09d3-417e-a5e0-aa09e99a3801\r\nCorrelation ID: 07b73f82-8cef-484e-bdf3-fccc382d68e5\r\nTimestamp: 2022-06-02 13:01:53Z”,“error_codes”:[90002],“timestamp”:“2022-06-02 13:01:53Z”,“trace_id”:“e36ac19c-09d3-417e-a5e0-aa09e99a3801”,“correlation_id”:“07b73f82-8cef-484e-bdf3-fccc382d68e5”,“error_uri”:"https://login.chinacloudapi.cn/error?code=90002"}
│
│ with provider[“Terraform Registry”].china,
│ on main.tf line 34, in provider “azurerm”:
│ 34: provider “azurerm” {
Expected Behavior
terraform should have skipped executing the data block with the provider argument.
Actual Behavior
data block is getting executed and provider block is getting called.
Steps to Reproduce
- Terraform script with 2 provider blocks and a data block with provider and count arguments. (count expression should return false)
- terraform init
- terraform plan (or) terraform apply