user2368632
user2368632

Reputation: 1073

How to deal with Terraform destroy operation when azure policy requires NSG on all subnets?

We have a policy on our subscription that forces all subnets to have an NSG. Terraform works well when creating the Subnet / NSG. However, it encounters policy error when doing terraform destroy because it tries to remove the NSG from the subnet first. This gets blocked because of the policy for requiring NSGs on all subnets. Is there a way to work around this in terraform or possibly make the subnet / nsg removal an atomic operation?

Terraform v0.11.13 + provider.azurerm v1.25.0

Upvotes: 3

Views: 739

Answers (1)

Christian Pearce
Christian Pearce

Reputation: 1026

This is a difficult problem to solve, and there are only sloppy solutions. I am speaking generically to handling policy with terraform. Essentially you want to inject the exclusion of a scope on the fly to the resource:

Options

  1. Simply go to the Azure Portal and exclude the policy on the resource prior to the destroy. If you disable the policy you need to put it back.
  2. Build an on the fly terraform for the policy assignment in a pipeline prior to a run which would add a not_scope for the targeted resource. Since the policy assignment is already deployed, a step of importing it will be required.
  3. Come up with a way of signaling a policy engine (what ever you are using automate your Azure policy). Add a not_scope that to your pipeline.
  4. Skip using terraform use Azure CLI or REST interface to update the scope.

For options 2, 3 or 4 a pause is needed for the policy assignment to become active. My experience is it will vary and sometimes fail, but if you are executing a pipeline you can alert on it and rerun.

Upvotes: 1

Related Questions