How to use resource reference into terraform workspace ? #9091

Currently, I am using terraform workspace to deploy the same code into multiple environments. But in right now i am stuck in referring resource in a specific workspace.

example of code

resource "aws_security_group" "testing-ec2" {
  name = "${local.env}-testing-ec2"
  vpc_id = "${aws_vpc.vpc.id}"
  ingress {
    from_port = 8080
    to_port = 8080
    protocol = "tcp"
    security_groups = ["${local.security-groups}"]
  }
  ingress {
    from_port = 22
    to_port = 22
    protocol = "tcp"
    cidr_blocks = ["${local.bastion_ip}"]
  }
  egress {
    from_port = 0
    to_port = 0
    protocol = -1
    cidr_blocks = ["0.0.0.0/0"]
  }
}

workspace security group

tf_security-groups = {
   dev = ""
   stg = "${aws_security_group.test-private-alb.id}"
   qa = "${aws_security_group.test1-private-alb.id}"
   prod = "${aws_security_group.test2-private-alb.id}"
 }
 security-groups = "${lookup(local.tf_security-groups,local.env)}"

when I am trying to apply into stg workspace this error appears

* local.tf_security-groups: local.tf_security-groups: Resource 'aws_security_group.test1-private-alb' not found for variable 'aws_security_group.test1-private-alb.id'

Hi @suvraroy
Try the tool terraform console to understand which values are you getting response.

I guess that you don’t need to create a locals with a map to lookup this values.
usually I’m using $ENVIRONMENT.tfvars, each environment with their respective values into its files. So you can run terraform plan -var-file stages/stg.tfvars and get less complexity in your code. (Just a suggestion)