0

我正在尝试cidr_blocks从资源的ingress规则中提取属性aws_security_group。我的 terraform 项目正在运行 version v0.11.13

模块A/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"]
  }
}

模块A/输出.tf

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

这给了我一个类似于以下的输出:

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"
 ...
}

但是,我无法仅提取 terraform 中的cidr_blocksusing查找函数,因为地图值的类型不同(有些是列表,有些是字符串)。我无法在 terraform12 中使用其他高级功能,因为该项目在 terraform11 中运行。

请提出一种从上述输出中仅提取 cidr_blocks 的方法,类似于以下内容。

预期输出:

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

或者

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

提前致谢。

4

1 回答 1

0

我找到了一种使用以下方法获得预期输出的方法:

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

在这里,我最初将地图转换为 json 对象并执行多个拆分和列表元素操作,以获得以下内容。

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

如果有人有更好和更清洁的解决方案,我将不胜感激。

于 2020-07-25T05:39:05.220 回答