1
votes

I have already created resource group(not created using my code).

I run terraform apply and my infra was created. But when I run terraform destroy - the console says that my resource group should be deleted too. This should not happen, because not only my infra is in this resource group.

I have try to use terraform import as described here https://stackoverflow.com/a/47446540/10912908 and got the same result as before.

Also, I have tried to define the resource group with only name, but it is not work(. Terraform destroy removes this resource

resource "azurerm_resource_group" "testgroup" {    
name = "Test-Group"    
}
2

2 Answers

3
votes

you have to not include resource group resource in the configuration for the resource group to not be destroyed (as all the resources in the configuration are to be destroyed). if you rely on outputs from that resource you can use data resource instead.

data "azurerm_resource_group" "test" {
  name = "Test-Group"
}

OP also needed to remove resource group from the state file.

1
votes

This bash script could work:

terraform state list | while read line
do 
if [[ $line == azurerm_resource_group* ]]; then
echo $line " is a resource group and will not be deleted!"
else
echo "deleting: " $line
terraform destroy -target $line -auto-approve
fi
done

It lists all resources which are managed by terraform and then runs a delete script for every entry except for lines containing "azurerm_resource_group*"