Can I get terraform to create resource A before creating resource B, while also deleting resource A before deleting resource B? In case of replacement this should be chained: delete A, then delete B, then create A, then create B.
The problem I have is with azurerm cdn custom domains and cname records. Custom CDN domains can only be created when an according DNS record exists. The can also be removed only, if the DNS record does not exist.
The problem is reproducible with the example in the official documentation
You could achieve something like that with the help of a null_resource
not quite sure how this will do in case of replacement
Here is a theoretical example:
resource "test" "a" {
}
resource "test" "b" {
depends_on = [ test.a ]
}
resource "null_resource" "delete" {
triggers = {
t = "abc"
}
provisioner "local-exec" {
when = destroy
command = "cmd to delete A"
}
depends_on = [ test.b ]
}
The null_resource
has the when = destroy
so the command will only run when we invoke a terraform destroy, we just need to be careful there not to create a circular reference
Here is another test I was just playing around with:
resource "local_file" "a" {
content = "aaaa"
filename = "${path.module}/a.txt"
}
resource "local_file" "b" {
content = "bbbb"
filename = "${path.module}/b.txt"
depends_on = [ local_file.a ]
}
resource "null_resource" "delete" {
triggers = {
t = "abc"
}
provisioner "local-exec" {
when = destroy
command = "rm a.txt; sleep 15"
}
depends_on = [ local_file.b ]
}
apply
local_file.a: Creating...
local_file.a: Creation complete after 0s [id=...]
local_file.b: Creating...
local_file.b: Creation complete after 0s [id=...]
null_resource.delete: Creating...
null_resource.delete: Creation complete after 0s [id=...]
destroy
null_resource.delete: Destroying... [id=...]
null_resource.delete: Provisioning with 'local-exec'...
null_resource.delete (local-exec): Executing: ["/bin/sh" "-c" "rm a.txt; sleep 15"]
null_resource.delete: Still destroying... [id=..., 10s elapsed]
null_resource.delete: Destruction complete after 15s
local_file.b: Destroying... [id=...]
local_file.b: Destruction complete after 0s
local_file.a: Destroying... [id=...]
local_file.a: Destruction complete after 0s
I added the sleep 15
to give me some time and manually verify that the file was deleted as intended, and yes it seems the order works without any hiccups, the resource a
sees the file is no longer there and completes the destroy process without any errors