0

We have a requirement to create a ec2 module and use it to create a ec2 instances (1 or more) + ebs device/ebs volume and use the same ec2 module to create ec2 (1 or more) w/o any ebs volumes.

I tried it via conditional (count) but hitting all sorts of errors. Help!

iaav
  • 484
  • 2
  • 9
  • 26
  • 1
    Can you provide more info to the issue like the error you've gotten – Palmer Feb 08 '19 at 15:59
  • I would really recommend using a ternary in `count` instead of relying on the casting of booleans into numbers, especially since both are not supported types until 0.12 and I think that behavior is changing too. – Matthew Schuchard Feb 08 '19 at 16:46

1 Answers1

0

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

Jake
  • 2,471
  • 15
  • 24
rclement
  • 1,664
  • 14
  • 10