TA-002-P · Question #376
You've used Terraform to deploy a virtual machine and a database. You want to replace this virtual machine instance with an identical one without affecting the database. What is the best way to…
The correct answer is A. Use the Terraform taint command targeting the VMs then run Terraform plan and Terraform apply. To replace a specific resource without affecting others, terraform taint marks the resource for recreation, and then terraform apply executes the replacement.
Question
You've used Terraform to deploy a virtual machine and a database. You want to replace this virtual machine instance with an identical one without affecting the database. What is the best way to achieve this using Terraform?
Options
- AUse the Terraform taint command targeting the VMs then run Terraform plan and Terraform apply
- BDelete the Terraform VM resources from your Terraform code then run Terraform plan and
- CUse the terraform apply command targeting the VM resources only
- DUse the terraform state rm command to remove the VM from state file
How the community answered
(18 responses)- A72% (13)
- B17% (3)
- C6% (1)
- D6% (1)
Why each option
To replace a specific resource without affecting others, terraform taint marks the resource for recreation, and then terraform apply executes the replacement.
The terraform taint command marks a specific resource as tainted, signaling to Terraform that it should be destroyed and recreated on the next terraform apply. This allows for controlled replacement of a single resource, like the VM, without impacting the database or other resources not explicitly marked.
Deleting VM resources from the Terraform code and running apply would remove the VM, but then you'd need to re-add it and apply again to get an identical one, which is more steps and not a direct replacement strategy.
Using terraform apply targeting only VM resources would only apply changes to that VM based on the current configuration, but it would not force a recreation unless the configuration itself changed in a way that necessitated recreation or if the resource was already tainted.
Using terraform state rm to remove the VM from the state file would make Terraform forget about the VM. Running terraform apply afterwards would then attempt to create a new VM if the resource is still defined in the HCL, but it would not destroy the existing VM, potentially leading to two VMs.
Concept tested: Terraform resource replacement - taint
Source: https://developer.hashicorp.com/terraform/cli/commands/taint
Topics
Community Discussion
No community discussion yet for this question.