1

Before deploying a virtual machine to proxmox using terraform, I need to make sure that the cloud-init configuration has been transferred through ssh. But I don't want that the config files of all virtual machines be transferred, instead I want just the one I'm currently deploying for. The problem is that I don't seem to be able to use a for_each variable as an index for that rule: This is what the resource look like:

resource "null_resource" "transfer_cloud_init" {
# trick using triggers and build_number to make the null_resource to execute each time and not store its state
        for_each = var.instances
        triggers = {
                build_number = "${timestamp()}"
        }
        connection {
                type = "ssh"
                user = "root"
                private_key = file("~/.ssh/id_ed25519")
                agent = false
                host = "pve1.example.com"
                port = 22
        }
        provisioner "file" {
                # if you use template:
                # source = local_file.cloud_init_ub2004
                source = "files/rendered-templates/cloud_init_ub2004-${each.key}.yaml"
                destination = "/mnt/pve/cloudinit/snippets/cloud_init_ub2004-${each.key}.yaml"
        }
}

And this is what I'm doing in the proxmox_vm_qemu resource:

resource "proxmox_vm_qemu" "proxmox_vm" {
        for_each = var.instances

# cloud-init config needs to exist before continuing
        depends_on = [
                null_resource.transfer_cloud_init["${each.key}"]
        ]

This errors out with:

╷
│ Error: Invalid expression
│
│   on main.tf line 90, in resource "proxmox_vm_qemu" "proxmox_vm":
│   90:         null_resource.transfer_cloud_init["${each.key}"]
│
│ A single static variable reference is required: only attribute access and indexing with constant keys. No
│ calculations, function calls, template expressions, etc are allowed here.

If I manually enter null_resource.transfer_cloud_init["username"], it works. Any ideas how I can loop correctly over this?

Lethargos
  • 625
  • 6
  • 14
  • No, I get it, I've searched the internet before also and this clearly seems to be a terraform limitation. It's just a bit annoying that I have to copy all those files every time for all virtual machines, even if I deploy one particular VM only. In this case it's not extremely badly, I suppose, but I'm definitely going to have more complex scenarios where this becomes more relevant. – Lethargos Dec 04 '21 at 09:32

1 Answers1

0

Any ideas how I can loop correctly over this?

It has too be static veritable, not dynamic:

        depends_on = [
                null_resource.transfer_cloud_init
        ]
Marcin
  • 215,873
  • 14
  • 235
  • 294