How to extract attributes from multi-type map in terraform11

223 views Asked by At

I am trying to extract the attribute cidr_blocks from an ingress rule of an aws_security_group resource. My terraform project is running version v0.11.13 .

moduleA/main.tf:

terraform {
  backend          "s3"             {}
  required_version = "0.11.13"
}

provider "aws" {
  region  = "us-east-1"
  version = "2.2.0"
}

...
# Create security group for CPS alb
resource "aws_security_group" "test" {
  name        = "test-sg"
  vpc_id      = "vpc-0xxxxxx"
  description = "Test security group"

  lifecycle {
    create_before_destroy = true
  }

  ingress {
    protocol    = "tcp"
    from_port   = 443
    to_port     = 443
    cidr_blocks = ["124.154.1.4/32","124.189.1.4/32"]
    description = "HTTPS access"
  }

  ingress {
    protocol    = "tcp"
    from_port   = 80
    to_port     = 80
    cidr_blocks = ["124.154.1.4/32","124.189.1.4/32"]
    description = "HTTP access"
  }

  egress {
    protocol    = -1
    from_port   = 0
    to_port     = 0
    cidr_blocks = ["0.0.0.0/0"]
  }
}

moduleA/outputs.tf

output "cidrs_allowed_ingress"{
  value = "${aws_security_group.test.ingress[0]}"
}

This gives me an output similar to the following:

cidrs_allowed_ingress = {
 cidr_blocks = ["124.154.1.4/32","124.189.1.4/32"]
 description = "HTTPS access"
 from_port = "443"
 to_port = "443"
 protocol = "tcp"
 ...
}

However I am unable to extract only the cidr_blocks using lookup function in terraform, because map values are not of same type(some are lists while some are strings). I cannot use other advanced features in terraform12 because the project runs in terraform11.

Please suggest a way to extract just the cidr_blocks from the above output similar to the following.

Expected output:

cidrs_allowed_ingress = ["124.154.1.4/32","124.189.1.4/32"]

or

cidrs_allowed_ingress = "124.154.1.4/32","124.189.1.4/32"

Thanks in advance.

1

There are 1 answers

0
harshainfo On

I found a way to obtain the expected output using the following:

output "cidrs_allowed_ingress"{
  value = "${element(split("\"cidr_blocks\":[", element(split("\"],", 
    jsonencode(aws_security_group.test.ingress[0])),0)),1)}\""
}

Here I am initially converting the map to a json object and do multiple split and list-element operations, to get the following.

cidrs_allowed_ingress = "124.154.1.4/32","124.189.1.4/32"

I would appreciate if somebody has a better and cleaner solution.