Machine machine = (Machine) execution.getVariable("machine");
checkNotNull(machine, "expecting a process variable named 'machine'");
LOG.info(">> Connecting to machine {} to run puppet script", machine);
SSHClient client = Ssh.newClient(machine, overrideAdminAccess(pool));
try {
for (Map.Entry<String, String> entry : createAdditionalFiles(pool, machine).entrySet()) {
Ssh.createFile(client, /* content = */ entry.getValue(), 0600, /* destination= */ entry.getKey());
}
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();
}
}