HCL2 and optional section

568 views
Skip to first unread message

Dan Linder

unread,
May 25, 2021, 10:04:37 PM5/25/21
to Packer
I'd like to present a single HCL2 Packer template to build some systems but I need to vary the number of "storage {}" sections, only provisioning a second disk if the "disk_size" setting for the second one is "> 0".

Does HCL2 have any "if" clauses, or if not is there a way using HCL2 to do this, or do I need to re-write my calling script to modify the HCL2 file before sending it to Packer?

Example:
I define the variables "root_disk_size" and "additional_disk_size", and the builder section has two "storage {}" sections:

storage {

  disk_size = var.root_disk_size

}

storage {

   disk_size = var.additional_disk_size

}

Is it possible to wrap the second section in a test something like "if var.additional_disk_size > 0"?

Megan Marsh

unread,
May 26, 2021, 2:50:42 PM5/26/21
to packe...@googlegroups.com
I think you should be able to do something like this:

```
variable "disk_size1" {
  default = 24
  type = number
}

variable "disk_size2" {
  default = 0
  type = number
}

locals {
  // use the ternary operator to define the storage elements
  storage = var.disk_size2 > 0 ? [var.disk_size1, var.disk_size2] : [var.disk_size1]
}

source "vsphere-iso" "basic-ubuntu" {
    // use a dynamic block to create the storage blocks based off your storage variable
    dynamic "storage" {
      for_each = local.storage

      content {
        disk_size = storage.value
      }
    }
```

--
This mailing list is governed under the HashiCorp Community Guidelines - https://www.hashicorp.com/community-guidelines.html. Behavior in violation of those guidelines may result in your removal from this mailing list.
 
GitHub Issues: https://github.com/hashicorp/packer/issues
IRC: #packer-tool on Freenode
---
You received this message because you are subscribed to the Google Groups "Packer" group.
To unsubscribe from this group and stop receiving emails from it, send an email to packer-tool...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/packer-tool/57a2a5bf-1fbc-4ed0-96bb-c4d55413dbffn%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages