When trying to conditionally create a resource, you can use a ternary to calculate the count
parameter.
A few notes:
- When using
count
, the aws_instance.example
, aws_ebs_volume.ebs-volume-1
, and aws_ebs_volume.ebs-volume-2
resources will be arrays.
- When attaching the EBS volumes to the instances, since the
aws_volume_attachment
resources have a count
, you can think of them as iterating the arrays to attach the volume to the EC2 instances.
- You can use
count.index
to extract the correct item from the array of the EC2 instances and the two EBS volume resources. For each value of count, the block is executed once.
variable "create_ebs" {
default = false
}
variable "instance_count" {
default = "1"
}
resource "aws_instance" "example" {
count = "${var.instance_count}"
ami = "ami-1"
instance_type = "t2.micro"
subnet_id = "subnet-1" #need to have more than one subnet
}
resource "aws_ebs_volume" "ebs-volume-1" {
count = "${var.create_ebs ? var.instance_count : 0}"
availability_zone = "us-east-1a" #use az based on the subnet
size = 10
type = "standard"
}
resource "aws_ebs_volume" "ebs-volume-2" {
count = "${var.create_ebs ? var.instance_count : 0}"
availability_zone = "us-east-1a"
size = 10
type = "gp2"
}
resource "aws_volume_attachment" "ebs-volume-1-attachment" {
count = "${var.create_ebs ? var.instance_count : 0}"
device_name = "/dev/sdf${count.index}"
volume_id = "${element(aws_ebs_volume.ebs-volume-1.*.id, count.index)}"
instance_id = "${element(aws_instance.example.*.id, count.index)}"
}
resource "aws_volume_attachment" "ebs-volume-2-attachment" {
count = "${var.create_ebs ? var.instance_count : 0}"
device_name = "/dev/sdg${count.index}"
volume_id = "${element(aws_ebs_volume.ebs-volume-2.*.id, count.index)}"
instance_id = "${element(aws_instance.example.*.id, count.index)}"
}
For more info on count.index
you can search for it on the Terraform interpolation page