'Condition based on date return
How can I create a condition based on returning a data if the resource doesn't exist?
I was trying the following but the error persists:
data "azurerm_private_dns_zone" "default" {
name = "kprivatelink.blob.core.windows.net"
resource_group_name = "my-dns"
}
output "my_output" {
value = try(data.azurerm_private_dns_zone.default.id, false) ? "yes" : "no"
}
Error:
│ Error: Private DNS Zone "kprivatelink.blob.core.windows.net" (Resource Group "my-dns") was not found
│
│ with data.azurerm_private_dns_zone.default,
│ on main.tf line 2, in data "azurerm_private_dns_zone" "default":
│ 2: data "azurerm_private_dns_zone" "default" {
│
Solution 1:[1]
You would have to develop your own custom data source. Since its fully custom, it can return whatever you want based on the existence of your resources. Then you use that in your conditions instead of azure provided resources.
Solution 2:[2]
The intended meaning of a singular data source in Terraform is to declare a dependency on an external object, meaning that the current configuration cannot be applied unless that object already exists.
Some providers do also offer data sources that can return information about zero or more objects matching a query, if the underlying API has such an operation, and that could in principle allow making a decision based on the length of the resulting collection. There doesn't seem to be such a data source available for the specific object type you asked about here.
Some of the use-cases people have in mind for this functionality are problematic in Terraform. In particular, it's not possible to write a declaration of the form "if this object doesn't exist then create it", because Terraform is a desired-state system and so you'd actually be stating a contradiction: "this object should exist only if it doesn't exist". Terraform will typically handle such a contradition by never converging on a stable state: the initial plan will propose to create the object, but then the next plan will propose to destroy it, and so on.
Instead, an important part of designing the architecture of your Terraform configurations is to decide ahead of time which objects are to be managed by which system, and then use data resources to handle the situation where an object managed by one system will be used by another.
The more appropriate use of a query-based data source that can produce multiple results is to help declare situations like "there should be one X for every existing Y", where X and Y are both different resource types. In that case, there is no contradiction and so the configurations can converge as long as the set of Y remains relatively stable, and changes only in situations where the set of X should also change.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marcin |
| Solution 2 | Martin Atkins |
