Search code examples
amazon-web-servicesterraformterraform-provider-awsterraform0.12+

Conditionally create aws_security_group_rule with count in terraform


I have following code in my terraform script

variable "sg_ingress_rules" {
  type = map(map(any))
  default = {
    port_22   = { from = 22, to = 22, proto = "tcp", cidr = "0.0.0.0/0", desc = "Allow port 22 from all" }
    port_3306 = { from = 3306, to = 3306, proto = "tcp", cidr = "10.0.0.0/8", desc = "Allow port 3306 from all" }
    port_3307 = { from = 3307, to = 3307, proto = "tcp", cidr = "10.0.0.0/8", desc = "Allow port 3307 from all" },
    port_3308 = { from = 3308, to = 3308, proto = "tcp", cidr = "10.0.0.0/8", desc = "Allow port 3308 from all" },
    port_9103 = { from = 9103, to = 9103, proto = "tcp", cidr = "10.0.0.0/8", desc = "Allow port 9103 from all" },
  }
}

resource "aws_security_group_rule" "mysql_ingress_rules" {
  for_each          = var.sg_ingress_rules
  type              = "ingress"
  from_port         = each.value.from
  to_port           = each.value.to
  protocol          = each.value.proto
  cidr_blocks       = [each.value.cidr]
  description       = each.value.desc
  security_group_id = aws_security_group.this[*].id
}

Now I want to conditionally create this rule only if I am creating mysql instance. It would not create any rule if launch_mysql is false. I tried this approach which is obviously wrong as you can't use both count and for_each.

resource "aws_security_group_rule" "mysql_ingress_rules" {
  count             = var.launch_mysql ? 1 : 0
  for_each          = var.sg_ingress_rules
  type              = "ingress"
  from_port         = each.value.from
  to_port           = each.value.to
  protocol          = each.value.proto
  cidr_blocks       = [each.value.cidr]
  description       = each.value.desc
  security_group_id = var.launch_mysql ? join("", aws_security_group.this[*].id) : "null"
}

I am using terraform version 1.0.2.

I am not able to think of any other way. Can someone please help me on this?


Solution

  • You can do this as follows:

    resource "aws_security_group_rule" "mysql_ingress_rules" {
    
      for_each          = var.launch_mysql ? var.sg_ingress_rules : {}
    
      type              = "ingress"
      from_port         = each.value.from
      to_port           = each.value.to
      protocol          = each.value.proto
      cidr_blocks       = [each.value.cidr]
      description       = each.value.desc
      security_group_id = aws_security_group.this[*].id
    }