Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从java运行ansible playbook_Ansible - Fatal编程技术网

从java运行ansible playbook

从java运行ansible playbook,ansible,Ansible,有没有一种方法可以从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) {

有没有一种方法可以从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();
        }
    }
}

您需要尝试使用那些
Reader
实例的资源,并且我相信您需要等到
waitFor
之后才能获取流内容,因为进程正在运行异步,但这些读取器没有使用异步,因此,过早地运行它们可能会丢失输出。可以从classpath i,e resources文件夹中读取yml文件或ansible playbooks和主机文件,并使用java执行吗