I'm trying to create a unique terraform plan that can automate the installation of 2 separate environments in 2 Azure tenants.
Environment A consists of:
- A container registry
- A kubernetes cluster
Environment B consists of:
- A kubernetes cluster that uses the registry in Environment A.
They will not share the same tfstate. We don't want to have to maintain 2 terraform plans.
Idea: (We cannot test the solution at the moment).
we create a variable.tf where we define a variable that will contain the registry Id.
variable.tf:
variable DeployRegistry {
default = "True" or "False" (True for envA, False for envB)
}
variable registry_acr_id {
default = "/subscriptions/xxx/resourceGroups/yyy/providers/Microsoft.ContainerRegistry/registries/zzz"
}
registry.tf creates the registry and set output:
resource "azurerm_container_registry" "acr" {
count = "${var.DeployRegistry == "true" ? 1 : 0}"
etc...
}
output "registry_acr_id" {
value = "azurerm_container_registry.acr.id
sensitive = false
}
With condition DeployRegistry set to false, we can disable the creation of the registry and use registry_acr_id passed as input (eventually in tfvar).
Question: Will it work or will output "registry_acr_id" be empty when we are not creating it? Because there is a condition to create or not the resource, but output is inconditionnally set.
CodePudding user response:
You probably want something like this:
variable "registry" {
type = string
default = null
}
locals {
registry = var.registry != null ? var.registry : azurerm_container_registry.acr[0].id
}
resource "azurerm_container_registry" "acr" {
count = var.registry == null ? 1 : 0
# ...
}
output "registry" {
value = local.registry
}
The above code creates and outputs the new registry if the variable "registry" is not set. If the registry is set to something, it assumes there is no need to create new one.