8

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

suhas
  • 227
  • 1
  • 3
  • 11

3 Answers3

32

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.

udondan
  • 57,263
  • 20
  • 190
  • 175
3

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.

Community
  • 1
  • 1
deimus
  • 9,565
  • 12
  • 63
  • 107
3

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
Punix81
  • 39
  • 2