I want to register a variable with my java version. I can get that with:
java -version 2>&1 | head -1 | awk ‘BEGIN { FS = “"” } ; { print $2 }’
That gives me the result I want: 1.8.0_45
But I cannot make this happen in ansible I’m going crazy with quotes and escapes. I’ve tried:
name: Get java version
shell: >
java -version 2>&1 | head -1 | awk ‘BEGIN { FS = “"” } ; { print $2 }’
register: java_ver
and:
name: Get java version
command: “{{ item }}”
with_items:
java -version 2>&1 | head -1 | awk ‘BEGIN { FS = “"” } ; { print $2 }’
register: java_ver
as well as trying various combinations of quotes and escape characters. I just can’t get the right recipe.
sivel
(sivel)
May 8, 2015, 9:44pm
2
Because I would rather use jinja2 than piping through a bunch of shell commands:
name: Run java -version
command: java -version
register: java_version_out
changed_when: false
name: Set java_version var
set_fact: java_version=“{{ java_version_out.stderr.splitlines()[0]|regex_replace(‘[^\d.]+’, ‘’) }}”
debug: var=java_version
Nice! However, your regex is also killing the underscore, and I need that. I’m starting to monkey around with this, but I just don’t know jinja, and I bet you’ll have the right magic sauce before I can puzzle it out
Thanks!
sivel
(sivel)
May 8, 2015, 10:04pm
4
You can add the underscore to the list of allowed characters in the regex_replace:
regex_replace(‘[^\d_.]+’, ‘’)