代码之家  ›  专栏  ›  技术社区  ›  Broshi

基于地图查找的var地形插值

  •  1
  • Broshi  · 技术社区  · 7 年前

    我已使用 Terraforming 有一个巨大的文件保存着所有的安全组。

    问题是,在每个安全组中都有一些规则,指的是安全组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
        }
    

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

    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 回复  |  直到 7 年前
        1
  •  2
  •   Koe    7 年前

    在terraform中访问map变量的方式如下

    ${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"]}
    
        2
  •  1
  •   Elad Shmitanka    7 年前

    按照建议,你需要把地图倒过来。您可以在原点反转(变量声明)或使用 transpose(map) 功能。 有点像

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

    可能工作