一千萬個為什麽

搜索

Terraform:如何在另一個變量中使用變量?



我試圖設計它,以便所有可配置的參數都存在於variables.tf中......我目前遇到的問題是配置EC2實例。我希望能夠定義要使用的安全組,但輸入變量只接受字符串,所以我無法引用安全組ID。

我繼續嘗試這個,它通過插入名稱動態地查找資源ID(請參閱security_groups_name和subnet_name:

variable "ansible_ami" { 
    type =  "map"
    default = {
            name = "ansible"
            ami = "ami-4836a428"
            size = "t2.micro"
            ebs_size = "8"
            ebs_type = "gp2" #general purpose ssd
            enable_public_ip = true
            security_groups_name = "JumpBox"
            subnet_name = "pubnet1"
    }
}


resource "aws_instance" "ansible" {
    ami = "${var.ansible_ami["ami"]}"
    instance_type = "${var.ansible_ami["size"]}"
    security_groups = "${aws_security_group.${var.ansible_ami["security_groups_name"]}.id}"
    subnet_id = "${aws_subnet.${var.ansible_ami["subnet_name"]}.id}"
    associate_public_ip_address = "${var.ansible_ami["enable_public_ip"]}"
    #user_data = ""

    ebs_block_device {
        device_name = "/dev/sdb"
        volume_size = "${var.ansible_ami["ebs_size"]}"
        volume_type = "${var.ansible_ami["ebs_type"]}"
    }

    tags {
        Name = "${var.ansible_ami["name"]}"
    }
}

然而,這是行不通的,因為我從我嘗試下一個變量的行中得到語法錯誤。我正在尋找關於如何實現這一點的想法或方向。

轉載註明原文: Terraform:如何在另一個變量中使用變量?

一共有 1 個回答:

主要受文檔的啟發,這個想法是創建一個terraform數據源來自可用資源的過濾器,然後將其用作您的ami資源中的入口點:

variable "security_group_id" {}
variable "subnet_id" {}

data "aws_security_group" "selected" {
  filter {
    name = "${var.ansible_ami["security_groups_name"]}}"
  }
}

data "aws_subnet" "selected" {
  filter {
    name = "${var.ansible_ami["subnet_name"]}"
  }
}

resource "aws_instance" "ansible" {
    ami = "${var.ansible_ami["ami"]}"
    instance_type = "${var.ansible_ami["size"]}"
    security_groups = "${data.aws_security_group.selected.id}"
    subnet_id = "${data.aws_subnet.selected.id}"
    associate_public_ip_address = "${var.ansible_ami["enable_public_ip"]}"
    #user_data = ""

我沒有使用terraform我自己,所以這可能是明顯錯誤的。