Manish Garedia
Manish Garedia

Reputation: 31

How do I dynamically create multiple disk using packer hcl

I am new to packer. Here's what I am trying to achieve. I want to create centos VM with either a single storage disk or double storage disk based on if vm-disk-size2 is defined or not. How can I pass the whole storage map via variables? Basically I am trying to pass "storage { disk_size = var.vm-disk-size, disk_thin_provisioned = true }" as a variable from the command-line or file.

source "vsphere-iso" "centos" {
  CPUs = var.vm-cpu-num
  RAM = var.vm-mem-size
  RAM_reserve_all = false
  boot_command = [
    "<tab> inst.text inst.ks=hd:fd0:/${ var.ks-file } <enter><wait>"
  ]
  boot_order = "disk,cdrom,floppy"
  boot_wait = "10s"
  cluster = var.vsphere-cluster
  communicator = "ssh"
  convert_to_template = true
  datastore = var.vsphere-datastore
  disk_controller_type = ["pvscsi"]
  floppy_files = [
    var.ks-file
  ]
  guest_os_type = "centos7_64Guest"
  host = var.vsphere-host
  insecure_connection = "true"
  iso_paths = [
    var.iso_url
  ]
  network_adapters {
      network = var.vsphere-network
      network_card = "vmxnet3"
    }
  notes = "Build via Packer"
  password = var.vsphere-password
  ssh_password = var.ssh_password
  ssh_username = "root"
  storage {
      disk_size = var.vm-disk-size
      disk_thin_provisioned = true
    }
    storage {
        disk_size = var.vm-disk-size2
        disk_thin_provisioned = true
      }
  username = var.vsphere_user
  vcenter_server = var.vsphere-server
  vm_name = var.vm-name
}

I am trying something like this with no luck yet..

  dynamic "storage" {
    for_each = var.storage
    content {
      disk_size = storage.key
      disk_thin_provisioned = true
    }
  }

and storage is defined as list variable in variables.pkr.hcl

variable "storage" { default = [] }

Running Packer like this:

packer build -var ks-file='"ks-2disk.cf"' -var storage='"["51200","25600"]"' .

Getting this error at this time: Error: Extra characters after expression

on line 1: (source code not available)

An expression was successfully parsed, but extra characters were found after it.

Upvotes: 1

Views: 1556

Answers (1)

Manish Garedia
Manish Garedia

Reputation: 31

I got it working by changing to

  dynamic "storage" {
    for_each = var.storage
    content {
      disk_size = storage.value
      disk_thin_provisioned = true
    }
  }

and

variable "storage" {
   type=list(string)
   default =  []
 }

Upvotes: 2

Related Questions