1
votes

When using the terraform-aws-modules/security-group/aws module, I can specify a CIDR_BLOCK with the string "10.211.103.254/32" but I cannot reference the variable that essentially contains the same value as verified by the terraform output:

Apply complete! Resources: 1 added, 4 changed, 1 destroyed.

Outputs:

blah_private_ip = 10.211.103.254/32

For example, the following code works

output "blah_private_ip" {
   value = "${aws_instance.SERVER-NAME-01.private_ip}/32"
}

module "blahsvr-sg" {
source = "terraform-aws-modules/security-group/aws"

name        = "blahsvr-sg"
description = "Security group for blah server"
vpc_id      = "${module.vpc.vpc_id}"

ingress_with_cidr_blocks = [
{
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    description = "HTTPS from server- managed by terraform"

    cidr_blocks = "10.211.103.254/32"  # works
    #cidr_blocks = "${var.blah_private_ip}"  # gives error
  },
]

egress_with_cidr_blocks = [
{
    from_port   = "0"
    to_port     = "65535"
    protocol    = "-1"
    description = "ALL"
    cidr_blocks = "0.0.0.0/0"
  },
  ]
}

However the same code but substituting the cidr_blocks line to reference the "${var.blah_private_ip}" variable instead yields the following terraform apply error:

 Error: module.gxesvr-sg.aws_security_group_rule.ingress_with_cidr_blocks[0]: "cidr_blocks.0" must contain a valid CIDR, got error parsing: invalid CIDR address:

I've also tried wrapping it in a CIDR block definition but I don't know what values to have for /32 (single IP address).

   cidr_blocks = "${cidrsubnet("${var.blah_private_ip}", 8, 0)}"
   cidr_blocks = "${cidrsubnet("${var.blah_private_ip}", 16, 0 )}"

Hope someone can help me to debug this.

1

1 Answers

1
votes

I don't see where you're defining the blah_private_ip variable. it doesn't seem to be the same as

output "blah_private_ip" {
   value = "${aws_instance.SERVER-NAME-01.private_ip}/32"
}

You should be able to just do ...

module "blahsvr-sg" {
  source = "terraform-aws-modules/security-group/aws"
  ...
  ingress_with_cidr_blocks = [
    {
    ...
    cidr_blocks = "${aws_instance.SERVER-NAME-01.private_ip}/32"
    ...
    }
  ]
}

rather than interpolate the ip output inside a variable (which you cannot do).

If you want to use the same value for output and as the ingress_with_cidr_blocks ->cidr input, you could define a local like so

locals {
  cidr = "${aws_instance.SERVER-NAME-01.private_ip}/32"
}


module "blahsvr-sg" {
  source = "terraform-aws-modules/security-group/aws"
  ...
  ingress_with_cidr_blocks = [
    {
    ...
    cidr_blocks = "${local.cidr}"
    ...
    }
  ]
}

output "my_cidr" {
  value = "${local.cidr}"
}