5

I am trying to configure my terraform for Dev and QA environments, each of which have their own Security Groups, which I specify with the data tag:

data "aws_security_group" "ssh" {
  name = "SG-SSH"
}

data "aws_security_group" "postgres" {
  name = "SG-Postgres"
}

Is there a way to specify which security groups get pulled in based on which environment is being targeted? I tried this:

locals {
  sgs = {
    dev  = ["${data.aws_security_group.postgres.id}", "${data.aws_security_group.ssh.id}"]
    qa   = ["${data.aws_security_group.postgres.id}"]
  }
}

Which I then reference with "${local.sgs[var.env]}". However, the ssh security group only exists in the Dev environment so when I target the QA environment, I still get:

data.aws_security_group.ssh: data.aws_security_group.ssh: no matching SecurityGroup found
covfefe
  • 2,485
  • 8
  • 47
  • 77

2 Answers2

0

As per the Terraform Documentation, you can specify conditional operations as follows:

CONDITION ? TRUEVAL : FALSEVAL

Then for example, you can define your security groups as follows:

locals {
  sgs = "${var.env == "dev" ? ["${data.aws_security_group.postgres.id}", "${data.aws_security_group.ssh.id}"] : ["${data.aws_security_group.postgres.id}"]}"
}

And call it with "${local.sgs}" - which will get all security groups based on the environment specified in var.env.

moebius
  • 2,061
  • 11
  • 20
0

The idea that moebius suggested is in right direction , but slightly wrong in the syntax, which is (according to Terraform Conditional Documentation

CONDITION ? TRUEVAL : FALSEVAL

So there should be only value passed both in when the condition is right or wrong.

So instead of

locals {
  sgs = "${var.env == "dev" ? ["${data.aws_security_group.postgres.id}", "${data.aws_security_group.ssh.id}"] : ["${data.aws_security_group.postgres.id}"]}"
}

Try using

locals {
  sgs = "${var.env == "dev" ? ["${data.aws_security_group.ssh.id}"] : ["${data.aws_security_group.postgres.id}"]}"
}