Destroy 'provisioner' for instance resources
Problem
I would be great to have sort of a 'provisioner' for destroying an instance resource. Example: When creating a instance, I bootstrap it with chef and the node is registered with the chef server. Now I need a way of automatically deleting the node from the chef server after terraform destroys the instance.
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Automate Node Deletion from Chef Server Post-Terraform Destroy
When an instance is destroyed using Terraform, the associated Chef node remains registered on the Chef server. This leads to stale nodes in the Chef server, which can clutter the environment and cause confusion during management.
Awaiting Verification
Be the first to verify this fix
- 1
Create a Local Script for Node Deletion
Develop a script that will delete the Chef node from the Chef server using the Chef API. This script will be triggered after the Terraform destroy command.
bash#!/bin/bash CHEF_NODE_NAME="<node_name>" # Delete the node from Chef server knife node delete $CHEF_NODE_NAME -y - 2
Integrate Script with Terraform
Use Terraform's local-exec provisioner to call the deletion script after the destroy action. This ensures that the script runs automatically when the instance is destroyed.
hclresource "null_resource" "delete_chef_node" { provisioner "local-exec" { command = "bash /path/to/delete_chef_node.sh" } depends_on = [aws_instance.my_instance] } - 3
Parameterize Node Name
Modify the deletion script to accept the node name as a parameter, allowing it to dynamically delete the correct node based on the instance being destroyed.
bash#!/bin/bash CHEF_NODE_NAME="$1" # Delete the node from Chef server knife node delete $CHEF_NODE_NAME -y - 4
Test the Integration
Run a Terraform destroy command on an instance that has been bootstrapped with Chef. Confirm that the node is deleted from the Chef server by checking the node list.
bashknife node list
Validation
After running the Terraform destroy command, verify that the Chef node is no longer listed by executing 'knife node list'. If the node is absent, the fix is successful.
Sign in to verify this fix
Environment
Submitted by
Alex Chen
2450 rep