How to ignore duplicate resource error during terraform apply? - terraform

I am trying to reapply my changes using terraform apply but when I am doing it again , it gives me error with resource already exists and stops the deployment .
Example:
Error: AlreadyExistsException: An alias with the name arn:aws:kms:us-east-1:490449857273:alias/continuedep-cmk-us-east-1 already exists
status code: 400, request id: 4447fd20-d33b-4c87-891e-cc5e09cc6108
on ../../../modules/kms_cmk/main.tf line 11, in resource "aws_kms_alias" "keyalias":
11: resource "aws_kms_alias" "keyalias" {
Error: Error creating DB Subnet Group: DBSubnetGroupAlreadyExists: The DB subnet group 'continuedep-sbg' already exists.
status code: 400, request id: 97d662b6-79d4-4fde-aaf7-a2f3e5a0bd9e
on ../../../modules/rds-postgres/main.tf line 2, in resource "aws_db_subnet_group" "generic_db_subnet_group":
2: resource "aws_db_subnet_group" "generic_db_subnet_group" {
Likewise i get errors with many other existing resources.I want to avoid/ignore such errors and continue my deployment .
What other way i can use from which I can restart my terraform resource deployment from where it is interrupted in the middle.
My terraform version is :
Terraform v0.12.9

The errors are returned by the API the Terraform provider is calling.
Possible causes of this could be:
you ( or someone else ) have executed your Terraform code and you don't have a shared / updated state
someone have created them manually
a Terraform destroy failed in a way that deleted the resources for the API but failed to save the update state
solutions depends on what you need. You can:
delete those resources from your Terraform code to stop managing them with it
delete those resources from the API ( cloud provider ) and recreate them with Terraform
Perform a terraform import of those resources and remove the terraform code that is trying to recreate them (NOT RECOMMENDED)
use terraform apply --target=xxx to apply only resources you need to apply (NOT RECOMMENDED)

Related

How to throw a warning or error in terraform plan?

I am currently writing a terraform custom provider for my internship project
The main aim of the project is to provision an environment (consisting of several servers) on a private cloud platform.
I created a custom provider using the CRUD operations.
Let's say I want to delete the whole resource by removing the whole resource block in main.tf. I want to do a terraform plan to see if the deletion is valid. It will do a read of the actual environment and see if the serverState of the server is active. I want it to throw a warning/error in terraform plan is serverState is not empty.
So the main issue right now is that the terraform plan only compares the difference between the configuration in main.tf and the actual tf statefile. So the error checking code in the delete function is not executed. It is only executed when terraform apply is used.
Is there any way to throw the error in terraform plan to warn the user before they use the terraform apply command

Unable to Execute Plan command and terraform provider file is being not created in PC after terraform init

I'm using terraform version v0.12.14. whenever I use terraform init I'm unable to see the terraform provider in my folder(hidden files are enabled to visible). also the plan command always fails with the error " no changes, infrastructure is up-to-date". kindly help me since I'm getting these errors I am not able to create the resource group in azure.

Diagnostic Settings - Master" already exists - to be managed via Terraform this resource needs to be imported into the State

I have a diagnostic setting configured on my master db. As shown below in my main.tf
resource "azurerm_monitor_diagnostic_setting" "main" {
name = "Diagnostic Settings - Master"
target_resource_id = "${azurerm_mssql_server.main.id}/databases/master"
log_analytics_workspace_id = azurerm_log_analytics_workspace.main.id
log {
category = "SQLSecurityAuditEvents"
enabled = true
retention_policy {
enabled = false
}
}
metric {
category = "AllMetrics"
retention_policy {
enabled = false
}
}
lifecycle {
ignore_changes = [log, metric]
}
}
If I don't delete it before in the resource group before I run the Terraform, I get the error:
Diagnostic Settings - Master" already exists - to be managed via
Terraform this resource needs to be imported into the State
I know that if I delete the SQL Server the diagnostic setting remains - but I don't know why that is a problem with Terraform. I have also noticed that it is in my tfplan.
What could be the problem?
If I don't delete it before in the resource group before I run the
Terraform, I get the error:
Diagnostic Settings - Master" already exists - to be managed via Terraform this resource needs to be imported into the State
I know that if I delete the SQL Server the diagnostic setting remains but I don't know why that is a problem with Terraform.
If you have created the resource in Azure from a different way (i.e. Portal/Templates/CLI/Powershell), that means Terraform is not aware of resource already existing in Azure. So, during Terraform Plan, it shows you the plan what will be created from what you have written in main.tf. But when you run Terraform Apply the azurerm provider checks the resources names with the existing resources of the same resource providers and result in giving an error that it already exists and needs to be imported to be managed by Terraform.
Also if you have created everything from Terraform then doing a Terraform destroy deletes all the resources present on the main.tf.
Well, it's in the .tfplan and also it's in main.tf - so it's imported, right ?
If you mention the resource and its details in main.tf and .tfplan, it doesn't mean that you have imported the resource or Terraform gets aware of the resource. Terraform is only aware of the resources that are stored in the Terraform state file i.e. .tfstate.
So , to overcome the error that you get without deleting the resource from Portal, you will have to add the resource in the main.tf as you have already done and then use Terraform import command to import the Azure resource to Terraform State file like below:
terraform import azurerm_monitor_diagnostic_setting.example "{resourceID}|{DiagnosticsSettingsName}"
So, for you it will be like:
terraform import azurerm_monitor_diagnostic_setting.main "/subscriptions/<SubscriptionID>/resourceGroups/<ResourceGroupName>/providers/Microsoft.Sql/servers/<SQLServerName>/databases/master|Diagnostic Settings - Master"
After the Import is done, any changes you make from Terraform to that resource will get reflected in portal as well and you will be able to destroy the resource from terraform as well.

how to handle corrupted terraform tfstate file

I am running an application inside pod in aks, that is provisioning a aws service using terraform, if that pod is deleted or stopped in between when provisioning is going on, the terraform state file is corrupted.
When I try provisioning again using that state file I get apply error. Some of the resources got provisioned but are not updated in the state file. I get following error.
Error: Error applying plan:
1 error(s) occurred:
* aws_s3_bucket.examplebucket: 1 error(s) occurred:
* aws_s3_bucket.examplebucket: Error creating S3 bucket: BucketAlreadyOwnedByYou: Your previous request to create the named bucket succeeded and you already own it.
status code: 409
so how to update the state file so I can use it again?
Not sure the error is related to kubernetes resources and pods.
But if you need refresh / recreate the bucket, you can taint it.
terraform taint aws_s3_bucket.examplebucket
terraform plan
terraform apply
Let me know if this is helpful or not.
If terraform tries to create something that already exists, you will need to import the resource into terraform.
Every kind of terraform resource, in this case a aws_s3_bucket, has listed in its documentation, at the bottom, on how to import it.
In this case, the following command should do the trick:
terraform import aws_s3_bucket.bucket **BUCKETNAME**
Replace BUCKETNAME with your bucket.

terraform apply fails while creating a resource that exists already

I am working on terraform with openstack as the cloud provider. I have a deploy.tf script that creates a role:
resource "openstack_identity_role_v3" "role_example" {
name = "creator"
}
My finding on how terraform creates resources:
If the role does not exist in openstack, terraform creates one with
no problem.
If the role exists in openstack and is created with the
same terraform script, ie. terraform.state has an entry of it,
terraform returns with no errors.
my issue is: if I remove the state file or if the role is created out of bands either manually or by some other terraform script.I get the following error:
* openstack_identity_role_v3.role_example: Error creating OpenStack role: Expected HTTP response code [201] when accessing [POST https://<example-openstack-url>/v3/roles], but got 409 instead
{"error": {"message": "Conflict occurred attempting to store role - Duplicate Entry", "code": 409, "title": "Conflict"}}
I am trying to find a workaround so that if the role doesn't exist, terraform apply creates it, and if it already exists, despite having created manually or by any other terraform deployment script, terraform skips its creation and throw no error.

Resources