}
final String destination = "/tmp/" + remoteFileName + ".pp";
Ssh.createFile(client, createPuppetScript(pool, machine), 0600, destination);
Session session = client.startSession();
try {
session.allocateDefaultPTY();
// TODO: extract this loop outside of this activity (probably using a business process error)
final String runScriptWithWaitCommand = "while ! which puppet &> /dev/null ; " +
"do echo 'Puppet command not found. Waiting for userdata.sh script to finish (10s)' " +
"&& sleep 10; " +
"done " +
"&& sudo puppet apply --detailed-exitcodes --debug --verbose " + destination;
Session.Command command = session.exec(runScriptWithWaitCommand);
Ssh.logCommandOutput(LOG, machine.getExternalId(), command);
command.join();
final Integer exitStatus = command.getExitStatus();
if (exitStatus != PUPPET_FINISHED_WITH_NO_FAILURES && exitStatus != 0) {
throw new RuntimeException(String.format("Failed to execute puppet. " +
"Exit code: %d. Exit message: %s", exitStatus, command.getExitErrorMessage()));
} else {
LOG.info("<< Command completed successfully with exit code 0");
}
} finally {
session.close();
}
} finally {
client.close();
}
}