terraform conditional resource

Viewed 5755

I have the following and I want to know what I am doing wrong, as I am sure I shouldn't have to double my code just because of a condition.

So I want to do:

variable "https" { value = true }

resource "aws_security_group" "http_instance_sg" {
  count       = "${var.https ? 0 : 1}"

  ......

}
resource "aws_security_group" "https_instance_sg" {
  count       = "${var.https ? 1 : 0}"

  ......

}

resource "aws_elb" "fe_elb" {
  security_groups = ["${var.https ? aws_aws_security_group.https_instance_sg.id : aws_aws_security_group.http_instance_sg.id}"]
   .....
}

But when I do this terraform complains that http_instance_sg cant be found, which I get it hasn't be built, but surely I dont have to double up on all the code and have:

 resource "aws_elb" "http_fe_elb" {
    count = "${var.https ? 0 : 1}"
    security_groups = ["${aws_aws_security_group.http_instance_sg.id}"]
   .....
  }

 resource "aws_elb" "https_fe_elb" {
    count = "${var.https ? 1 : 0}"
    security_groups = ["${aws_aws_security_group.https_instance_sg.id}"]
   .....
  }
3 Answers

Do you try to add depends_on instruction ? Something like this (I'm not sure about the syntax) :

resource "aws_elb" "fe_elb" { depends_on = [ aws_aws_security_group.https_instance_sg, aws_aws_security_group.http_instance_sg ] security_groups = ["${var.https ? aws_aws_security_group.https_instance_sg.id : aws_aws_security_group.http_instance_sg.id}"] ..... }

Related