Check Java version via Ansible playbook

2019-07-17 06:44发布

问题:

Following is my playbook:

---
- hosts: UAT
  gather_facts: false
  remote_user: xxxx
  become_method: sudo
  become: yes
  become_user: sudo_user
  tasks:
   - name: Fetch Java version
     command: java -version
     register: java_result
     ignore_errors: True
   - debug: "msg={{ java_result.stdout }}"
...

And I am getting the below error:

fatal: [ma-dsast-lapp10]: FAILED! => {
    "changed": false,
    "cmd": "java -version '2>&1' '|' grep version",
    "failed": true,
    "invocation": {
        "module_args": {
            "_raw_params": "java -version 2>&1 | grep version",
            "_uses_shell": false,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "warn": true
        }
    },
    "msg": "[Errno 2] No such file or directory",
    "rc": 2
}

Im getting : No such file or directory error

What could be the issue with this? Please help me on this.

回答1:

I ran your script on my machine and it did not work either. I modified it a little bit

---

- hosts: localhost
  gather_facts: False

  tasks:
   - name: Fetch Java version
     shell: java -version 2>&1 | grep version | awk '{print $3}' | sed 's/"//g'                                                                                                                                   
     changed_when: False
     register: java_result

   - debug:
       msg: "{{ java_result.stdout }}"

And I got

TASK [debug] *******************************************************************************************
ok: [localhost] => {
    "msg": "1.8.0_181"
}