Kumar Madduri
Kumar Madduri

Reputation: 145

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

Upvotes: 7

Views: 20633

Answers (1)

Mark B
Mark B

Reputation: 201138

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]

Upvotes: 20

Related Questions