Terraform Tutorial - destroy
In this article, we're going to go over how to completely destroy the Terraform-managed infrastructure.
Resources can be destroyed using the terraform destroy
command, which is similar to terraform apply
but it behaves as if all of the resources have been removed from the configuration.
Ref - https://www.terraform.io/intro/getting-started/destroy.html
$ terraform destroy aws_key_pair.terraform-demo: Refreshing state... (ID: terraform-demo) aws_instance.my-instance: Refreshing state... (ID: i-0aab39eec884aa165) aws_instance.import_example: Refreshing state... (ID: i-0df15e8dabc165c5f) An execution plan has been generated and is shown below. Resource actions are indicated with the following symbols: - destroy Terraform will perform the following actions: - aws_instance.import_example - aws_instance.my-instance - aws_key_pair.terraform-demo Plan: 0 to add, 0 to change, 3 to destroy. Do you really want to destroy all resources? Terraform will destroy all your managed infrastructure, as shown above. There is no undo. Only 'yes' will be accepted to confirm. Enter a value:
Answer yes to execute this plan and destroy the infrastructure:
aws_instance.my-instance: Destroying... (ID: i-0aab39eec884aa165) aws_instance.import_example: Destroying... (ID: i-0df15e8dabc165c5f) ... aws_key_pair.terraform-demo: Destroying... (ID: terraform-demo) ... Destroy complete! Resources: 3 destroyed.
Similar to apply
, Terraform determines the order in which things must be destroyed. In more complicated cases with multiple resources, Terraform will destroy them in a suitable order to respect dependencies.
provider.tf:
provider "aws" { region = "${var.aws_region}" }
ec2-instance.tf:
resource "aws_key_pair" "terraform-demo" { key_name = "terraform-demo" public_key = "${file("terraform-demo.pub")}" } resource "aws_instance" "import_example" { ami = "${lookup(var.ami,var.aws_region)}" instance_type = "${var.instance_type}" key_name = "${aws_key_pair.terraform-demo.key_name}" } resource "aws_instance" "my-instance" { count = "${var.instance_count}" ami = "${lookup(var.ami,var.aws_region)}" instance_type = "${var.instance_type}" key_name = "${aws_key_pair.terraform-demo.key_name}" user_data = "${file("install_apache.sh")}" tags = { Name = "${element(var.instance_tags, count.index)}" Batch = "5AM" } } output "ip" { value = "${aws_instance.my-instance.*.public_ip}" }
vars.tf:
variable "ami" { type = "map" default = { "us-east-1" = "ami-04169656fea786776" "us-west-1" = "ami-006fce2a9625b177f" } } variable "instance_count" { default = "1" } variable "instance_tags" { type = "list" default = ["Terraform-1", "Terraform-2"] } variable "instance_type" { default = "t2.nano" } variable "aws_region" { default = "us-east-1" }
Terraform
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization