首页 文章

Terraform Interpolation进入带有 Map 查找的var

提问于
浏览
0

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

问题是,在每个安全组中都有一些规则引用了安全组ID - 在我计划运行terraform的新区域中不存在这些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 = ["sg-25bee542"] <-- this ID doesnt exists in the new region i'm planning to work on
        self            = false
    }

我已经创建了一个包含所有旧安全组的 Map :

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 回答

  • 2

    您在terraform中访问 Map 变量的方式是这样的

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

    如果你想获得sg_ID,你可以反过来创建 Map .

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

    然后使用

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

    如建议的那样,您需要反转 Map . 你可以在原点(变量声明)中反转它或使用 transpose(map) 函数 . 就像是

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

    可能有用

相关问题