Run ansible playbook from java



有没有一种方法可以从java执行ansible playbook。你能帮我参考一下吗?找不到任何好的教程。

最简单的方法是使用ProcessBuilder:运行命令

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class AnsibleServive {
public static void main(String[] args) {
runCommand("ansible-playbook test.yml -i host.ini");
}
private static void runCommand(String command) {
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("bash", "-c", command);
try {
Process process = processBuilder.start();
StringBuilder output = new StringBuilder();
StringBuilder errOutput = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line + "n");
}
BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((line = errReader.readLine()) != null) {
errOutput.append(line + "n");
}
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println("Command Successfully executed.");
System.out.println(output);
} else {
System.err.println("Error ocured during running command.");
System.out.println(output);
System.err.println(errOutput);
}
} catch (IOException | InterruptedException e) {
System.err.println("Failed to execute command.");
e.printStackTrace();
}
}
}

最新更新