Error: deleting WAFv2 WebACL - How to unassign WAF from the CloudFront and delete it


We have a simple configuration with CloudFront and conditionally added WAF, but with modules.

Adding works fine, but when we are trying to set waf_enable = false, Terraform firstly trying to remove WAF and then probably to update CloudFront distribution, which is not a right order.

module "cloudfront" {
  source = "./modules/cloudfront"

    web_acl_id  = var.waf_enable ? module.waf.web_acl_id : null


Terraform will perform the following actions:

  # module.cloudfront.aws_cloudfront_distribution.common will be updated in-place
  ~ resource "aws_cloudfront_distribution" "common" {
        id                             = "E3R2RYBFLFA9P2"
        tags                           = {}
      - web_acl_id                     = "arn:aws:wafv2:us-east-1:123456789012:global/webacl/common/c45decba-fdfe-4e26-a919-7c2ea7a24139" -> null

  # module.waf.aws_wafv2_web_acl.common[0] will be destroyed

module.waf.aws_wafv2_web_acl.common[0]: Still destroying… [id=c45decba-fdfe-4e26-a919-7c2ea7a24139, 5m0s elapsed]

│ Error: deleting WAFv2 WebACL (c45decba-fdfe-4e26-a919-7c2ea7a24139): WAFAssociatedItemException: AWS WAF couldn’t perform the operation because your resource is being used by another resource or it’s associated with another resource.

Is there a way to manage this removal order?

Thank you!

With all that, terraform destroy is handling all in a right order and all resources are destroyed.

So, we are able to

  1. Create everything with WAF
  2. Create everything without WAF and then assign it
  3. Destroy everything

But it is not clear how to optionally remove and destroy just WAF.