Specifying security group in a cidr_blocks

I am attempting to enable SSH between the head node and a cluster of compute nodes (and among the compute nodes themselves)

In the AWS console, I am allowed to use a security group as input to the cidr_blocks

How can I achieve the same via Terraform HCL ?

resource “aws_security_group” “head_node_sg” {
name = “head_node_sg”
description = “Allow SSH inbound traffic”

ingress {
from_port = 22
to_port = 22
protocol = “tcp”
cidr_blocks = [“0.0.0.0/0”]
}

egress {
from_port = 0
to_port = 0
protocol = “-1”
cidr_blocks = [“0.0.0.0/0”]
}
}

resource “aws_security_group” “compute_node_sg” {
name = “compute_node_sg”
description = “Allow SSH inbound traffic”

ingress {
from_port = 22
to_port = 22
protocol = “tcp”
cidr_blocks = [
aws_security_group.head_node_sg.id
]
}

egress {
from_port = 0
to_port = 0
protocol = “-1”
cidr_blocks = [“0.0.0.0/0”]
}
}

I would recommend that you create the two groups without any in-line rules.
Then, create two security group rules:

resource "aws_security_group_rule" "inbound_ssh" {
  type            = "ingress"
  from_port       = 22
  to_port         = 22
  protocol        = "tcp"
  source_security_group_id = aws_security_group.head_node_sg.id

  security_group_id = aws_security_group.compute_node_sg.id
}

resource "aws_security_group_rule" "outbound_ssh" {
  type            = "egress"
  from_port       = 22
  to_port         = 22
  protocol        = "tcp"
  source_security_group_id = aws_security_group.compute_node_sg.id

  security_group_id = aws_security_group.head_node_sg.id
}

It’s a lot easier to use securitygroups in this fashion, sort of as labels which are used by the rules. You don’t need to worry about ip addresses that changes or wrong machines in a subnet.

Thank you @bentterp, I have implemented that.