I am writing a Test case using ansible.There are totally 9 servers in which I need to check whether the installed java version is 1.7.0 or not?
If it is less than 1.7.0 then test case should fail.
Can anyone help me to write this Test case as I am very new to ansible.
Thanks in advance
1 Answer 1. Ansible does not have a module to directly check the versions of any program. You have two options, both involving a bash command to extract the version number from the output of your scripts.
If you want to check the Java version on Ubuntu, Debian or CentOS operating systems, open a command-line terminal and run the following command: ? ? OpenJDK Runtime Environment (build 11.0.9.1+1-Ubuntu-0ubuntu1.20.04) You can also check the Java compiler version using the javac command as shown below:
- name: Check if java is installed command: java -version become_user: ' { { global_vars.user_session }}' // your user session register: java_result ignore_errors: True - debug: msg: "Failed - Java is not installed" when: java_result is failed - debug: msg: "Success - Java is installed" when: java_result is success
But avoid … Asking for help, clarification, or responding to other answers. Making statements based on opinion; back them up with references or personal experience. To learn more, see our tips on writing great answers. Not the answer you're looking for? Browse other questions tagged java shell scripting ansible version or ask your own question.
Ansible has a version_compare
filter since 1.6. But since Ansible doesn't know about your Java version you first need to fetch it in a separate task and register the output, so you can compare it.
- name: Fetch Java version
shell: java -version 2>&1 | grep version | awk '{print $3}' | sed 's/"//g'
register: java_version
- assert:
that:
- java_version.stdout | version_compare('1.7', '>=')
On a sidenote, if your main use case for Ansible is to validate the server state you might want to have a look at using an infrastructure test tool instead: serverspec, goss, inspec, testinfra.
Altough in your question you havn't specified what have you tried, but still
You can run a commands like this
ansible your_host -m command -a 'java -version'
If you need to parse the output of java -version
there is a very good script from Glenn Jackman here adapt it to your needs and use it.
If you are still looking for help, be more specific and show what you tried to do.
Since 2.0 you can make this
- name: Check if java is installed
command: java -version
become_user: '{{ global_vars.user_session }}' // your user session
register: java_result
ignore_errors: True
- debug:
msg: "Failed - Java is not installed"
when: java_result is failed
- debug:
msg: "Success - Java is installed"
when: java_result is success
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With