Its hard to do because you're not really supposed to do it that way
Or at least thats what I read when I was trying to do something similar.
Could you set up public/private keys and do passwordless authentication?
That is much easier to script, though it is "riskier" since it links the two machines quite closely. But a) its a VM so if the server is compromised they have "physical access" to the VM anyway and b) you are saving ssh-keys unencrypted the way you are doing it now anyway, so this is probably more secure.