使用 for_each 将不同数量的磁盘附加到不同数量的 VM

如何解决使用 for_each 将不同数量的磁盘附加到不同数量的 VM

TF 版本:0.13.4

提供者版本:2.40.0

我不确定最好/最有效的方法来做到这一点,但我想要实现的是将 2 个磁盘(目前)附加到每个 VM,但我需要能够配置每个 VM和磁盘根据要求。将来我可能需要改变磁盘和 VM 的数量。我试图让 for_each 循环遍历大小,并根据其中有多少个值,创建该数量的磁盘,以便我可以拥有多个不同大小的磁盘。

有没有一种无需手动创建多个托管磁盘资源的方法?

我当前的代码创建了不同数量的 VM,但每个 VM 只附加一个磁盘。 for_each 迭代的变量在每个环境的 tfvars 文件中设置:

desktop_servers = {
  "Server_1" = {
    name = 1,zone = 1,lun  = 1,size = 32
  }
  "Server_2" = {
    name = 2,zone = 2,lun  = 2,size = 32
  }

  "Server_3" = {
    name = 3,zone = 3,lun  = 3,size = 32
  }
}

etl_servers = {
  "Server_1" = {
    name = 1,size = 32
  }
}

module.tf 内的虚拟机资源

# Azure Virtual Machine
resource "azurerm_windows_virtual_machine" "virtual_machine" {
  for_each                         = var.servers
  name                             = "vm-${var.environment}-${var.vm_identifier}${each.value.name}"
  location                         = var.location
  resource_group_name              = var.resource_group
  zone                             = each.value.zone
  size                             = var.vm_size
  network_interface_ids            = [azurerm_network_interface.network_interface[each.key].id]
  computer_name                    = "${var.vm_identifier}${each.value.name}"
  admin_username                   = xxxx
  admin_password                   = xxxx
  provision_vm_agent               = "true"
  source_image_id                  = data.azurerm_shared_image.dwp_shared_image.id


  boot_diagnostics {
    storage_account_uri = data.azurerm_storage_account.dwp_diag_storage_account.primary_blob_endpoint
  }

  os_disk {
    name                      = "vm-${var.environment}-${var.directorate}-${var.business_unit}-${var.vm_identifier}-os${each.value.name}"
    caching                   = "ReadWrite"
    storage_account_type      = "Premium_LRS"
  }

  depends_on = [azurerm_network_interface.network_interface]
}

module.tf 中的托管磁盘资源:

# #Managed disks per vm
resource "azurerm_managed_disk" "managed_disk" {
  for_each               = var.servers
  name                   = "disk-${var.environment}-${var.vm_identifier}${each.value.name}"
  location               = var.location
  resource_group_name    = var.resource_group
  storage_account_type   = "Premium_LRS"
  create_option          = "Empty"
  disk_size_gb           = each.value.size
  zones                  = [azurerm_windows_virtual_machine.virtual_machine[each.key].zone]
}

resource "azurerm_virtual_machine_data_disk_attachment" "disk_attachment" {
  for_each           = var.servers
  managed_disk_id    = azurerm_managed_disk.managed_disk[each.key].id
  virtual_machine_id = azurerm_windows_virtual_machine.virtual_machine[each.key].id
  lun                = each.value.lun
  caching            = "ReadWrite"
}

模块内的variable.tf:

variable "servers" {
  description = "Variable for defining each instance"
}

main.tf 中 ETL 服务器的模块示例。 :

module "etl_vm" {
  source                       = "../modules/compute/windows_vm"
  location                     = var.location
  resource_group               = azurerm_resource_group.rg_sbox_etl.name
  directorate                  = var.directorate
  business_unit                = var.business_unit
  environment                  = var.environment
  network_rg_identifier        = var.network_rg_identifier
  subnet_name                  = "sub-${var.environment}-${var.directorate}-${var.business_unit}-be01"
  diag_storage_account_name    = var.diag_storage_account_name
  log_analytics_workspace_name = var.log_analytics_workspace_name
  backup_policy_name           = var.backup_policy_name
  vm_identifier                = "${var.vm_identifier}${var.instance_number}-etl"
  servers                      = var.etl_servers
  vm_size                      = var.etl_vm_size
  enable_management_locks      = true
  image_name                   = "WIN2016-CISL2"
  gallery_subscription_id      = var.sub_id
  gallery_resourcegroup        = var.rg_gallery
  gallery_name                 = "SBOXGallery"

解决方法

您可以使用模块来实现它。但这有点复杂。思路是你使用模块来配置VM,在每个VM中,你可以配置不同的数据盘,并把它们附加到VM上。使用该变量输入不同的配置虚拟机号。下面是一个例子:

main.tf

ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        Network activeNetwork = cm.getActiveNetwork();
        NetworkCapabilities networkCapabilities = cm.getNetworkCapabilities(activeNetwork);
        int signalStrength = networkCapabilities.getSignalStrength();

terraform.tfvar

variable "rg_name" {
    type = string
}

variable "vms" {
    type = map(object({
        size = string
        admin_user = string
        admin_password = string
        disks = list(number)
    }))
}

variable "location" {}

module "vms" {
    for_each = var.vms
    
    source = "./modules/vm"
    resource_group_name = var.rg_name
    vm_name = each.key
    vm = each.value
    disks = each.value["disks"]
    location = var.location
}

./modules/vm/main.tf

rg_name = "charlesVMs"
location = "East US"
vms ={
  azurevm1 = {
    
    size = "Standard_DS1_v2"
    admin_user = "azureuser"
    admin_password = "azureuser@2021"
    disks = [30,30]
  }
}

您只需为 variable "resource_group_name" {} variable "vm" {} variable "disks" {} variable "location" {} variable "vm_name" {} resource "azurerm_resource_group" "example" { name = var.resource_group_name location = var.location } resource "azurerm_virtual_network" "example" { name = "example-network" address_space = ["10.0.0.0/16"] location = azurerm_resource_group.example.location resource_group_name = azurerm_resource_group.example.name } resource "azurerm_subnet" "example" { name = "internal" resource_group_name = azurerm_resource_group.example.name virtual_network_name = azurerm_virtual_network.example.name address_prefixes = ["10.0.2.0/24"] } resource "azurerm_network_interface" "example" { name = "example-nic" location = azurerm_resource_group.example.location resource_group_name = azurerm_resource_group.example.name ip_configuration { name = "internal" subnet_id = azurerm_subnet.example.id private_ip_address_allocation = "Dynamic" } } resource "azurerm_linux_virtual_machine" "vm" { name = var.vm_name resource_group_name = azurerm_resource_group.example.name location = azurerm_resource_group.example.location size = var.vm["size"] disable_password_authentication = false admin_username = var.vm["admin_user"] admin_password = var.vm["admin_password"] network_interface_ids = [ azurerm_network_interface.example.id ] # admin_ssh_key { # username = "adminuser" # public_key = file("~/.ssh/id_rsa.pub") # } os_disk { caching = "ReadWrite" storage_account_type = "Standard_LRS" } source_image_reference { publisher = "Canonical" offer = "UbuntuServer" sku = "16.04-LTS" version = "latest" } } resource "azurerm_managed_disk" "example" { count = length(var.vm["disks"]) name = "datadisk-${count.index}" location = azurerm_resource_group.example.location resource_group_name = azurerm_resource_group.example.name storage_account_type = "Standard_LRS" create_option = "Empty" disk_size_gb = element(var.vm["disks"],count.index) } resource "azurerm_virtual_machine_data_disk_attachment" "example" { count = length(var.vm["disks"]) managed_disk_id = element(azurerm_managed_disk.example.*.id,count.index) virtual_machine_id = azurerm_linux_virtual_machine.vm.id lun = count.index caching = "ReadWrite" } 变量提供不同数量的 VM 配置和不同数量的磁盘和大小。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-