【问题标题】:How can I create multiple VMs through Terraform?如何通过 Terraform 创建多个 VM?
【发布时间】:2020-01-08 07:01:18
【问题描述】:

我有一个请求为不同的服务器创建多个虚拟机,例如:

{
  "type"   = "ansibleserver"
  "size"   = "Standard_DC2s"
  "count" = 2
},
{
  "type"   = "frontendserver"
  "size"   = "Standard_DC2s"
  "count" = 2
},
{
  "type"   = "backendserver"
  "size"   = "Standard_L8s_v2"
  "count" = 3
}

对于所有 3 种服务器,我必须以不同的大小和数量创建它们,现在我只能以非常糟糕的方式来做:

resource "azurerm_virtual_machine" "ansibleserver" {
  count = "${lookup(var.ansibleserver, "count")}"

  name  = 
  ......
}

resource "azurerm_virtual_machine" "frontendserver" {
  count = "${lookup(var.frontendserver, "count")}"

  name  = 
  ......
}

那么如果有新的需求进来,我不仅要改变量,还要改脚本,太复杂了。有没有什么方法可以更体面地改变整个创建过程,比如代码中的for循环?

【问题讨论】:

  • 什么版本的 Terraform?

标签: azure terraform


【解决方案1】:

参考link中提到的建议,让我知道状态

这个 GitHub article 应该可以帮助你

更多信息可以参考link中提到的建议。

你正在寻找这样的东西:

resource "azurerm_virtual_machine" "server" {
  name                  = "server-${count.index}"
  count                 = "${var.instance_count}"
  …
  storage_os_disk {
    name              = "server-${count.index}-os"
    caching           = "ReadWrite"
    create_option     = "FromImage"
    managed_disk_type = "Standard_LRS"
  }
} 

其他信息:azurerm_virtual_machine

Need to create multile vms in azure through terraform

如果以上内容有帮助,或者您在此问题上需要进一步帮助,请告诉我们。

【讨论】:

    【解决方案2】:

    这里的第一个任务是将您的输入扁平化到一个集合中,其中每个元素只对应一个虚拟机:

    locals {
      servers_flat = flatten([
        for s in var.servers : [
          for n in range(s.count) : {
            type  = s.type
            size  = s.size
            index = n
          }
        ]
      ])
    }
    

    完成此操作后,您可以使用for_each 为集合的每个元素创建一个资源实例。

    resource "azurerm_virtual_machine" "ansibleserver" {
      for_each = { for s in var.servers_flat : format("%s%02d", s.name, s.index) => s }
    
      name = each.key # a string like "ansibleserver01"
      size = each.value.size
    }
    

    我们必须通过转换为映射来给每个元素一个唯一的键,所以这里我假设“类型”在输入列表中应该是唯一的,因此将它与索引结合起来就足以产生一个唯一的键。如果不是这样,您可能还需要在键中包含 size 字符串,方法是调整 for_each 中的键表达式。

    这样做的结果将是具有azurerm_virtual_machine.ansibleserver["ansibleserver01"] 之类地址的实例,因此当您在未来向列表中添加或删除元素时,Terraform 将能够与现有实例相关联,以确定它需要创建或销毁什么,不会打扰无关的实例。

    【讨论】:

      猜你喜欢
      • 2017-03-25
      • 1970-01-01
      • 2021-09-26
      • 1970-01-01
      • 2022-09-28
      • 1970-01-01
      • 2020-07-04
      • 2022-01-26
      • 1970-01-01
      相关资源
      最近更新 更多