Terraform Interpolation进入带有地图查找的var

时间:2018-06-05 15:06:00

标签: terraform

我已使用Terraforming导出了当前资源,并获得了一个包含所有安全组的大文件。

问题是,在每个安全组中都有一些规则引用了安全组ID - 这些规则在我计划运行terraform的新区域中不存在。例如:

resource "aws_security_group" "my-group" {
    name        = "my-group"
    description = ""
    vpc_id      = "${var.vpc["production"]}"

    ingress {
        from_port       = 80
        to_port         = 80
        protocol        = "tcp"
        security_groups = ["sg-25bee542"] <-- this ID doesnt exists in the new region i'm planning to work on
        self            = false
    }

我已经创建了一张包含所有旧安全组的地图:

variable "security_groups" {
    type    = "map"
    default = {
        "sg-acd22fdb" = "default"
        "sg-52cd3025" = "my-group"
        "sg-25bee542" = "my-group2"
        ...
    }
}

现在我正在尝试将硬编码sg-*id*解析为相应的安全组名称并将其插入到变量中,以便第一个示例以这种方式工作:

resource "aws_security_group" "my-group" {
    name        = "my-group"
    description = ""
    vpc_id      = "${var.vpc["production"]}"

    ingress {
        from_port       = 80
        to_port         = 80
        protocol        = "tcp"
        security_groups = ["${aws_security_group.my-group2.id}"] <-- the 'my-group2' should be resolved from the map variable
        self            = false
    }

类似的东西:

resource "aws_security_group" "my-group" {
    name        = "my-group"
    description = ""
    vpc_id      = "${var.vpc["production"]}"

    ingress {
        from_port       = 80
        to_port         = 80
        protocol        = "tcp"
        security_groups = ["${aws_security_group.[lookup(security_groups,sg-25bee542]].id}"] <-- the 'my-group2' string should be resolved from the map variable by looking its sg ID
        self            = false
    }

我希望我在这个问题上明确表达......任何想法?

2 个答案:

答案 0 :(得分:2)

您在terraform中访问地图变量的方式就像这样

${var.security_groups["sg-acd22fdb"]}

如果你想获得sg_ID,你可以反过来创建地图。

variable "security_groups" {
    type    = "map"
    default = {
        "default = "sg-acd22fdb"
        "my-group" = "sg-52cd3025"
        "my-group2" = "sg-25bee542"
        ...
    }
}

然后使用

${var.security_groups["my-group2"]}

答案 1 :(得分:1)

根据建议,您需要反转地图。您可以在原点(变量声明)处反转它或使用transpose(map)函数。

之类的东西
${transpose(var.security_groups)["sg-acd22fdb"]}

可能有效