I have deployed an azure postgresql flexible server using terraform. The terraform code is in a submodule and I include it in the main.tf like this:
module "postgresql" {
source = "./modules/postgreSQL"
pg_name = "${var.pg_name}"
private_dns_zone = "${var.pg_private_dns_zone}"
location = data.azurerm_resource_group.resource_group.location
resource_group_name = data.azurerm_resource_group.resource_group.name
...
...
}
The module creates the flexible servers azurerm_postgresql_flexible_server
and a couple of databases azurerm_postgresql_flexible_server_database
I tried to create a new flexible server using the point_in_time_restore_time_in_utc
feature and importing twice my module with different parameters and the PITR time
module "postgresql" {
source = "./modules/postgreSQL"
pg_name = "${var.pg_name}"
private_dns_zone = "${var.pg_private_dns_zone}"
location = data.azurerm_resource_group.resource_group.location
resource_group_name = data.azurerm_resource_group.resource_group.name
...
...
}
# New restored Database
module "postgresql_new" {
source = "./modules/postgreSQL"
pg_name = "new${var.pg_name}"
private_dns_zone = "new${var.pg_private_dns_zone}"
location = data.azurerm_resource_group.resource_group.location
resource_group_name = data.azurerm_resource_group.resource_group.name
...
...
point_in_time_restore_time_in_utc = "2024-09-22T11:53:37.249000Z"
source_server_id = module.postgresql.pg_id
create_mode = "PointInTimeRestore"
}
Terraform apply fails because it cannot create the databases azurerm_postgresql_flexible_server_database
since they are created automatically by Azure with the restore procedure and not by Terraform. Here the errors thrown by terraform
Error: A resource with the ID "/subscriptions/xxxxx/resourceGroups/rgr-zzzz-dev/providers/Microsoft.DBforPostgreSQL/flexibleServers/yyyyy/databases/mydb"
already exists - to be managed via Terraform this resource needs to be imported into the State.
Please see the resource documentation for "azurerm_postgresql_flexible_server_database" for more information.
How can I solve this issue? or there is another way/workflow that I can use to restore a flexible server in Azure using terraform?
You need to import that resource into Terraform How to import resources into Terraform
example:
import {
to = azurerm_postgresql_flexible_server_database
id = "/subscriptions/xxxxx/resourceGroups/rgr-zzzz-dev/providers/Microsoft.DBforPostgreSQL/flexibleServers/yyyyy/databases/mydb"}