Search code examples
terraformterraform-provider-awsaws-batch

Terraform: How to enable deletion of batch service compute environment?


I have stood up infrastructure using Terraform, including a batch service job queue, compute environment, and job definition.

After making changes to the Terraform I have run terraform apply and get the following error:

Error: error deleting Batch Compute Environment (data-load): : Cannot delete, found existing JobQueue relationship
    status code: 400, request id: 25449415-9c36-4748-95e6-925647bd716a

There are no jobs in the job queue. I assumed it would be removed/replaced along with other resources associated with the batch service rather than holding up the show for the compute environment as it's being replaced.

In the past, the only way I could get past this was to nuke my state file and start afresh, but I assume there must be a better way. How can I get past this issue?


Solution

  • When a resource is recreated in Terraform, it will be deleted and created in order by default. So if compute_environment_nameyou change and apply only, the computing environment on which the job queue depends temporarily does not exist, so you will die as follows. Error: Error applying plan:

    
    1 error(s) occurred:
    
    * aws_batch_compute_environment.sample (destroy): 1 error(s) occurred:
    
    * aws_batch_compute_environment.sample: error deleting Batch Compute Environment (sample): : Cannot delete, found existing JobQueue relationship
    
    

    Therefore, compute_environment_namechange create_before_destroy = trueand specify the lifecycle explicitly.

    
    resource "aws_batch_compute_environment" "sample" {
      compute_environment_name = "sample-v2"
                         ...
        instance_type = [
          "m5",
        ]
                         ...
      lifecycle {
        create_before_destroy = true
      }
    }