I am working on a task where where the requirement is to create an RDS instance, run initial sql script on it to create databases and users.
To achieve this, I am planning two step approach
resource "aws_db_instance" "my_db" {
#details
}
resource "aws_instance" "my_db_sql_script_runner_instance" {
#details
provisioner "remote-exec" {
#run sql script
}
}
Now I want to delete this EC2 instance automatically once the SQL script is executed (as it's a one time task).
The code runs on CI/CD. Therefore running terraform destroy -resource <resource>
is not possible. And I am not really open (and allowed) to change the existing CI/CD pipeline.
I was looking for something like resource "destroy_resource" "ec2_instance_resource"
in the same terraform file. Is there any way we can acheive this?
This sort of imperative action is not something Terraform is designed to handle. Terraform is designed for long-lived infrastructure which can be changed to match what's described in the configuration over time.
Terraform is therefore not the appropriate tool for this use-case. Imperative actions like these would be better handled using imperative techniques, such as using the AWS CLI in a script or using the AWS SDK in a program you write in a programming language of your choice (assuming it has an AWS SDK available).