Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract security group id from security group name in terraform

I am trying to write a generic script in terraform to create ALB (in AWS). The security groups are created (sg_alb) but not in the same script. It is pre-created I want to extract the id of the security group and pass it security_groups = ["${aws_security_group.lb_sg.id}"]

I have seen examples where the above reference is made but that is assuming the security group is created along with ALB

How can I achieve this ?

Thank you Kumar

like image 895
Kumar Madduri Avatar asked Jan 25 '23 05:01

Kumar Madduri


1 Answers

This is what Terraform data sources are for. If your Terraform module is getting a security group name as a variable, then you would look up the security group like this:

data "aws_security_group" "lb_sg" {
  name = var.security_group_name
}

Then you could use the data source when creating your ALB, like this:

security_groups = [data.aws_security_group.lb_sg.id]
like image 75
Mark B Avatar answered Feb 08 '23 17:02

Mark B