[Solved] Access the build port during build


I am experimenting with a qemu builder setup.

I would like to set the host port forwarding manually. This would allow me to also run external scripts (ansible, terraform, chef …) against the running instance. But for this to work I need to expose the port.

Maybe there is a simpler way, but what I tried to do is:

qemu_args = [["-nic", "user,model=virtio,hostfwd=tcp::${build.Port}-:22"]]

The part of interrest is:


According to the documentation, this should be possible for provisioners: Contextual Variables - HCL Configuration Language | Packer | HashiCorp Developer

But I need to know this during build time.
From the logs I can also see that the lookup and assignment of the port happens before the actual run step. Therefore the port would be known at that time, but I could not find any way to access it.

I guess these are some relevant areas:

Thanks :slight_smile:

1 Like

Reading the documentation more closely I found the answer myself:

  qemuargs = [
    [ "-device", "virtio-net,netdev=forward,id=net0"]
    [ "-netdev", "user,hostfwd=tcp::{{ .SSHHostPort }}-:22,id=forward"],

For some reason the above example did not work for me, always resulting in a qemu error that it is unable to create the forwarding. It also failed for me when using the -nic option.
In both cases the arguments did work when running from console without packer, but failed when running with packer :person_shrugging:

I could make it work by using another example from the documentation and combined it to:

            "hostfwd=tcp::{{ SSHHostPort }}-:22,",