Your code works for me as written, but while testing it I mis-typed the path and got the same behavior as you.
Because you're using a shell
task with a pipe, if the first command in the pipe fails the error is effectively suppressed. Consider this:
$ false | echo hello
hello
$ echo $?
0
The first command fails, but there's no way to tell. That's exactly the behavior I was seeing running the playbook locally, and it may be the cause of your problem.
If you copy and paste the full command line into your shell and run it, does it work? What if you just copy and paste the ../java -version
part?
For this sort of task it's often simpler to do the text parsing in ansible rather than using awk
; something like this:
- hosts: localhost
gather_facts: false
tasks:
- name: Fetch Java version from location
command: /usr/java/jdk-17.0.2/bin/java -version
register: java_version_from_path
- name: Display the java version from the java location
debug:
msg: >-
{{
(
java_version_from_path.stderr_lines |
select('search', 'version') |
first
).split('"')[1]
}}
On my system, this produces:
TASK [Fetch Java version from location] *****************************************************************
changed: [localhost]
TASK [Display the java version from the java location] **************************************************
ok: [localhost] => {
"msg": "17.0.2"
}
By performing the text parsing in Ansible, we can use a command
task, rather than shell
, and without that shell pipeline errors in the java
command will propagate to the playbook and we'll see the failure:
TASK [Fetch Java version from location] *****************************************************************
fatal: [localhost]: FAILED! => {"changed": false, "cmd": "/usr/java/jdk-1.8/bin/java -version", "msg": "[Errno 2] No such file or directory: b'/usr/java/jdk-1.8/bin/java'", "rc": 2, "stderr": "", "stderr_lines": [], "stdout": "", "stdout_lines": []}