I have a simple AWS CloudFormation template for creating a hosted zone for example.com
along with an SSL/TLS certificate for that domain. It looks something like this:
…
Resources:
HostedZone:
Type: AWS::Route53::HostedZone
Properties:
Name: example.com
Certificate:
Type: AWS::CertificateManager::Certificate
Properties:
DomainName: example.com
ValidationMethod: DNS
DomainValidationOptions:
- DomainName: example.com
HostedZoneId: !Ref HostedZone
I had understood that if I don't specify a DeletionPolicy
, by default CloudFormation deletes resources in a stack when a stack is deleted. There are a few exceptions such as a non-empty S3 bucket, but that makes sense because in that case someone went in and added things to the bucket independent of the CloudFormation stack I presume.
However when I delete the stack for the above template, I get an error:
The specified hosted zone contains non-required resource record sets and so cannot be deleted. (Service: Route53, Status Code: 400, Request ID: …)
Of course the error message is understandable: an extra record was added to the hosted zone in order to verify the certificate, and the hosted zone can't be deleted unless you first delete that extra record. The same thing would happen if I created all this manually.
Still that behavior isn't really consistent with the documentation of DeletionPolicy
(which says resources should be deleted automatically), and there is nothing here that wasn't created by the stack. It would seem that, despite all the assurances that "CloudFormation is declarative" and "CloudFormation figures out the order in which to do things", it comes with a lot of caveats at least when it comes to deletion.
In this case CloudFormation should figure out that it added the record after creating the hosted zone, so it should remove that record before deleting the hosted zone. But it can't figure that out.
If CloudFormation can figure out how to delete the hosted zone (which it can), and if CloudFormation can figure out how to remove the load balancer (which it can), and if CloudFormation can figure out how to remove the record from the hosted zone pointing to the load balancer before deleting the hosted zone (which it can), why can't CloudFormation figure out how to delete the certificate verification record from the hosted zone before deleting the hosted zone?
Is there some workaround to add to my stack definition to allow the hosted zone to be deleted when the stack is deleted? If I have to go in and manually remove a record every time, it defeats the purpose of CloudFormation as far as deletion is concerned.