Add a Security Group to the Inbound Rule of another Security Group as a Source with Terraform (AWS)

2.8k views Asked by At

I couldn't add the security group "sg0" to the inbound rule of another security group "sg1" as a source with Terraform. (I use Terraform v0.15.4)

This is the code I tried:

resource "aws_security_group" "sg0" {
    ..........
}

resource "aws_security_group" "sg1" {
    ..........

    ingress {
      from_port        = 5432
      to_port          = 5432
      security_groups  = [aws_security_group.sg0]
      protocol         = "tcp"
    }
    ..........
}

But I got the error below:

Error: Incorrect attribute value type
│ 
│   on main.tf line 235, in resource "aws_security_group" "sg1":
│  235:       security_groups  = [aws_security_group.sg0]
│     ├────────────────
│     │ aws_security_group.sg0 is object with 13 attributes
│ 
│ Inappropriate value for attribute "security_groups": element 0: string required.

I want to get the same result as the below which I did manually without Terraform. How can I do this?

enter image description here

2

There are 2 answers

0
Super Kai - Kazuya Ito On

You need to add the security group id of "sg0" to the inbound rule of "sg1" as a source. So you need to add only .id after aws_security_group.sg0 like below.

resource "aws_security_group" "sg0" {
    ..........
}

resource "aws_security_group" "sg1" {
    ..........

    ingress {
      from_port        = 5432
      to_port          = 5432
      security_groups  = [aws_security_group.sg0.id] # Add .id here!!
      protocol         = "tcp"
    }
    ..........
}
0
Bunty On

Update your security group sg1 configuration with either of below changes,

resource "aws_security_group" "sg0" {
    ..........
}

resource "aws_security_group" "sg1" {
    ..........

    ingress {
      from_port                = 5432
      to_port                  = 5432
      source_security_group_id = aws_security_group.sg0.id
      protocol                 = "tcp"
    }
    ..........
}

[OR]

resource "aws_security_group" "sg0" {
    ..........
}

resource "aws_security_group" "sg1" {
    ..........
      type                     = ingress
      from_port                = 5432
      to_port                  = 5432
      source_security_group_id = aws_security_group.sg0.id
      security_group_id        = aws_security_group.sg01.id
      protocol                 = "tcp"
    ..........
}