从 java 运行 ansible-playbook

blo*_*old 5 java ansible

我一直在尝试使用 Java(runtime().exec() 和 ProcessBuilder)运行 anisble-playbooks,在这两种情况下,我发现我希望使用命令行传递的额外变量永远不会被执行,或者看起来是这样。

ProcessBuilder builder = new ProcessBuilder("ansible-playbook", "/root/playbooks/script-ilo.yml", "-e", "'@/tmp/vars.yml'");
Run Code Online (Sandbox Code Playgroud)

String[] ansible_run = {"ansible-playbook", "/root/playbooks/script-ilo.yml", "-e", "'@/tmp/vars.yml'"};
Process p = Runtime.getRuntime().exec(ansible_run,null);
Run Code Online (Sandbox Code Playgroud)

我将代码打包为 jar 并在测试系统中执行,在这两种情况下,ansible 都会运行 playbook 并抛出错误。

# java -jar /home/admin/test-script.jar

PLAY [esxi] ********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [192.168.50.100]

TASK [Set XML with new secrets] ************************************************
fatal: [192.168.50.100]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'change_user' is undefined\n\nThe error appears to have been in '/root/playbooks/script-ilo.yml': line 3, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n  tasks:\n    - name: Set XML with new secrets\n      ^ here\n"}
        to retry, use: --limit @/root/playbooks/script-ilo.retry

PLAY RECAP *********************************************************************
192.168.50.100             : ok=1    changed=0    unreachable=0    failed=1
Run Code Online (Sandbox Code Playgroud)

ansible-playbook /root/playbooks/script-ilo.yml -e '@/tmp/vars.yml' 当我在 shell 中运行该命令时,它运行完美。

我需要帮助来解除这里的封锁。如果有更好的方法来做到这一点,我洗耳恭听。

mda*_*iel 4

String[] ansible_run = {"ansible-playbook", "/root/playbooks/script-ilo.yml", "-e", "'@/tmp/vars.yml'"};

不要在该-e值中添加单引号;单引号仅在您的 shell 中需要,但ProcessBuilder不会通过您的 shell,因此不需要对参数进行转义。

当我公然喂给 ansible 一个 bogus 时,我实际上期望 ansible 会发牢骚-e,但事实证明任何这样的值都会传递给 as hostvars_raw_params所以在你的情况下,它会设置一个像这样的值:

"hostvars": {
    "192.168.50.100": {
        "_raw_params": "'@/tmp/vars.yml'",
Run Code Online (Sandbox Code Playgroud)