iT邦幫忙

2023 iThome 鐵人賽

DAY 16
0

原簡體中文教程連結: Introduction.《Terraform入門教程》


1.5.3.1. 模組元參數

在 Terraform 0.13 之前,模組在使用上有一些限制。例如我們透過模組來建立 EC2 主機,可以這樣:

module "ec2_instance" {
  source  = "terraform-aws-modules/ec2-instance/aws"
  version = "~> 3.0"

  name = "single-instance"

  ami                    = "ami-ebd02392"
  instance_type          = "t2.micro"
  key_name               = "user1"
  monitoring             = true
  vpc_security_group_ids = ["sg-12345678"]
  subnet_id              = "subnet-eddcdzz4"

  tags = {
    Terraform   = "true"
    Environment = "dev"
  }
}

如果我們要建立兩台這樣的主機怎麼辦?在 Terraform 0.13 之前的版本中,由於 Module 不支援元參數,所以我們只能手動拷貝模組程式碼:

module "ec2_instance_0" {
  source  = "terraform-aws-modules/ec2-instance/aws"
  version = "~> 3.0"

  name = "single-instance-0"

  ami                    = "ami-ebd02392"
  instance_type          = "t2.micro"
  key_name               = "user1"
  monitoring             = true
  vpc_security_group_ids = ["sg-12345678"]
  subnet_id              = "subnet-eddcdzz4"

  tags = {
    Terraform   = "true"
    Environment = "dev"
  }
}

module "ec2_instance_1" {
  source  = "terraform-aws-modules/ec2-instance/aws"
  version = "~> 3.0"

  name = "single-instance-1"

  ami                    = "ami-ebd02392"
  instance_type          = "t2.micro"
  key_name               = "user1"
  monitoring             = true
  vpc_security_group_ids = ["sg-12345678"]
  subnet_id              = "subnet-eddcdzz4"

  tags = {
    Terraform   = "true"
    Environment = "dev"
  }
}

自從 Terraform 0.13 開始,模組也像資源一樣,支援 countfor_eachdepends_on 三種元參數。比如我們可以這樣:

module "ec2_instance" {
  count = 2
  source  = "terraform-aws-modules/ec2-instance/aws"
  version = "~> 3.0"

  name = "single-instance-${count.index}"

  ami                    = "ami-ebd02392"
  instance_type          = "t2.micro"
  key_name               = "user1"
  monitoring             = true
  vpc_security_group_ids = ["sg-12345678"]
  subnet_id              = "subnet-eddcdzz4"

  tags = {
    Terraform   = "true"
    Environment = "dev"
  }
}

要注意的是 Terraform 0.13 之後在模組上聲明 depends_on,列表中也可以傳入另一個模組。聲明 depends_on 的模組中的所有資源的創建都會發生在被依賴的模組中所有資源創建完成之後。


原簡體中文教程連結: Introduction.《Terraform入門教程》


上一篇
Day15-【入門教程】引用模組
下一篇
Day17-【入門教程】重構
系列文
Terraform 繁體中文25
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言