Search code examples
amazon-web-servicesterraformhcl

Terraform assign variable to a lit block


I use the aws provider. For each security group I specify same rule for ssh. How to extract it to a variable and assign to aws_security_group.ingress list?

What do I expect:

variable "ssh_ingress" {
  default = {
    from_port = 22
    protocol = "tcp"
    to_port = 22
    description = "SSH for administration."
  }
}
resource "aws_security_group" "main" {
  ingress += var.ssh_ingress // That not work.

  ingress {
    from_port = 0
    protocol = "-1"
    to_port = 0
    self = true
  }

}

Solution

  • You could use aws_security_group_rule add rules to existing security group.

    For example:

    variable "ssh_ingress" {
      default = {
        from_port = 22
        protocol = "tcp"
        to_port = 22
        description = "SSH for administration."
      }
    }
    
    resource "aws_security_group" "main" {
      name        = "allow_tls"
      description = "Allow TLS inbound traffic"
      vpc_id      = data.aws_vpc.main.id
    }
    
    resource "aws_security_group_rule" "default" {
      type              = "ingress"
      from_port         = 0
      to_port           = 0
      protocol          = -1
      self              = true
      security_group_id = aws_security_group.main.id
    }
    
    resource "aws_security_group_rule" "example" {
      type              = "ingress"
      from_port         = var.ssh_ingress.from_port
      to_port           = var.ssh_ingress.to_port
      protocol          = var.ssh_ingress.protocol
      cidr_blocks       = ["10.0.0.0/11"]
      security_group_id = aws_security_group.main.id
    }
    

    Alternative wiht multiple inline ingress rules

    resource "aws_security_group" "main" {
      name        = "allow_tls"
      description = "Allow TLS inbound traffic"
      vpc_id      = data.aws_vpc.main.id
      
      ingress {
        from_port = 0
        protocol = "-1"
        to_port = 0
        self = true
      }
      
     ingress {
       from_port         = var.ssh_ingress.from_port
       to_port           = var.ssh_ingress.to_port
       protocol          = var.ssh_ingress.protocol
       cidr_blocks       = ["10.0.0.0/11"]
      }
      
    }