Allen99
Allen99

Reputation: 13

Ansible to check for Java and install if not already on RHEL machines

Trying to create a job that will check for java and install if it comes back as not installed. All works with the exception of the install part. Ansible is telling me a conditional has not been met so it skips the install.

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

- name: print java version
  debug:
    msg: " {{ java_result.stdout }} "
  when: java_result.rc==0

- name: install java version
  yum: 
    name: java-1.8.0-openjdk.x86_64
    present: yes
  when: java_result.rc!=0

The end result that works:

- name: fetch java version
  shell: java -version
  changed_when: False
  register: java_result
  failed_when: False

- name: install java version
  yum:
    name: java
    state: latest       
  when: java_result.rc!=0
  become: yes
  become_user: root

thanks.

Upvotes: 1

Views: 2980

Answers (1)

lxop
lxop

Reputation: 8605

The problem is that your shell command is a pipeline, and the result value of a pipeline is (by default) the result of the last command in the pipeline. In this case it is sed, which will be closing normally, so will have a rc of 0.

There are a number of ways you could solve this problem; the first one that comes to mind is to change your shell command to only run java -version. Then you can check the rc value of that command: if it is non-zero then install java, if it is zero then you can do some fancy regex to extract the version string and print it.

Or, you could check directly for the existence of the java executable with the stat module.

Or, you could just run the yum block without checking for java first - if the package is already installed, it won't do anything. That's probably the most Ansibley way to do it.

Upvotes: 2

Related Questions