enter image description hereI am deploying some azure policy assignment using Terra-form via git-lab Ci/Cd, and our state-file is git-lab managed when i am applying these policies i am getting error 1 resource is already exist.
already exists – to be managed via Terraform this resource needs to be imported into the State. Please see the resource documentation for "azurerm_subscription_policy_assignment" for more information.
2
Answers
The error message you’re encountering in Terraform indicates that the Azure Policy Assignment you’re trying to create already exists in the Azure environment, but it’s not present in your Terraform state file. Terraform needs to have a record of all managed resources in the state file to operate correctly.
Import the Existing Policy Assignment: You need to import the existing policy assignment into your Terraform state. You can do this with the
terraform import
command, which will require the ID of the existing policy assignment in Azure. The import command will look something like this (replace<POLICY_ASSIGNMENT_ID>
with the actual ID):The
<INDEX>
would be the index of yourfor_each
loop where this particular resource is defined.My demo configuration tried to check the incident with preexisting subscription policy assignment info in my local
My terraform configuration:
Output:
Now I run the command to import the infrastructure into my remote statefile
Now I run the commands
then continue with terraform commands later on.
To import you can use the import block in your tf file:
After that, you can simply run the terraform apply and it will import into your tfstate file. If desired, you can later remove the import block, and it should keep the imported policy in your state file, or you can also keep it to know the history of this resource.
https://camargo-wes.medium.com/how-to-import-an-existing-azure-resource-into-your-terraform-state-with-azure-storage-backend-2f6cbdee5927
https://developer.hashicorp.com/terraform/language/import