Count:
Before Terraform 0.12.6, the only way to create multiple instances of the same resource was to use a count parameter. One of the problems with this approach is ordering. Count is maintaining the array numeric index (list) to perform it's operations.If there is a change in the order, terraform wants to destroy/re-create that object.Code snippet has been given below to explain the difference between count and for_each. Given snippet has been taken from block volume provisioning & attachment module.
Phase 1: Provision the block volumes
Below code will provision three block volumes("MyVolume1","MyVolume2","jay") and attach the same to the defined compute instance.
variable "block_display_name" {
type = "list"
default = ["MyVolume1","MyVolume2","jay"]
}
type = "list"
default = ["MyVolume1","MyVolume2","jay"]
}
variable "block_size" {
type = "list"
default = ["50","60","80"]
}
type = "list"
default = ["50","60","80"]
}
block.tf
resource "oci_core_volume" "gol_blockvolume" {
count = "${var.vol_count}"
availability_domain = "${data.oci_identity_availability_domain.ad.name}"
compartment_id = "${var.compartment_id}"
display_name = "${var.block_display_name[count.index]}"
size_in_gbs = "${var.block_size[count.index]}"
}
resource "oci_core_volume_attachment" "gol_attachment" {
count = "${var.vol_count}"
depends_on = ["oci_core_volume.gol_blockvolume"]
attachment_type = "iscsi"
instance_id = "${data.oci_core_instances.gol_instances.instances.*.id[0]}"
volume_id = "${oci_core_volume.gol_blockvolume.*.id[count.index]}"
}
count = "${var.vol_count}"
availability_domain = "${data.oci_identity_availability_domain.ad.name}"
compartment_id = "${var.compartment_id}"
display_name = "${var.block_display_name[count.index]}"
size_in_gbs = "${var.block_size[count.index]}"
}
resource "oci_core_volume_attachment" "gol_attachment" {
count = "${var.vol_count}"
depends_on = ["oci_core_volume.gol_blockvolume"]
attachment_type = "iscsi"
instance_id = "${data.oci_core_instances.gol_instances.instances.*.id[0]}"
volume_id = "${oci_core_volume.gol_blockvolume.*.id[count.index]}"
}
Let us run terraform plan to review the resource actions.