testingvirtual-machinepackerhashicorp-packertestinfra

Download file from VM built by Packer even if a previous provisioner fails


I am build VM images using Hashicorp Packer and test those images at the end of the build using Testinfra.

Now I want to download a test report of my tests. This basically works fine with the file provisioner:

build {
  sources = [
    "sources.vmware-iso.vmware"
  ]

  [...]

  provisioner "shell" {
    inline = ["py.test --junit-xml /tmp/testreport.xml -v /tmp/test.py"]
  }

  provisioner "file" {
    destination = "${var.build_dir}/testreport.xml"
    direction   = "download"
    source      = "/tmp/testreport.xml"
  }
}

MY problem is, that this only works if all tests succeed. Otherwise, the shell provisioner running the tests returns an error code and Packer terminates the build immediately. But I would like to have the test report to be downloaded even in case of an error. Is this possible somehow?


Solution

  • Lets try to use error-cleanup-provisioner.

    This is example from Packer documentation, but you can try to use file instead of shell-local

    source "null" "example" {
      communicator = "none"
    }
    
    build {
      sources = ["source.null.example"]
    
      provisioner "shell-local" {
        inline = ["exit 2"]
      }
    
      error-cleanup-provisioner "shell-local" {
        inline = ["echo 'rubber ducky'> ducky.txt"]
      }
    }
    

    https://developer.hashicorp.com/packer/docs/templates/hcl_templates/blocks/build/provisioner#on-error-provisioner