Ansible Playbook – How to Get Extra Vars Java Link, Download, and Extract

ansibleansible-playbookbash

I want to download java from http://download.oracle.com/otn-pub/java/jdk/8u131-b11/d54c1d3a095b4ff2b6607d096fa80163/jdk-8u131-linux-x64.tar.gz

then extract it

tar -xzvf jdk-8u131-linux-x64.tar.gz

but not able to do it

I have the below ansible playbook code

- name: Download Java to Latest Version
      shell: |
              mkdir /opt/java
              cd /opt/java
              wget -c --header "Cookie: oraclelicense=accept-securebackup-cookie" {{javaurl}}
              tar -xzvf ${javaurl##*/} 
   
    - debug:
        msg: "The Java sdk is {{javaurl##*/}}"

I did pass the url from ansible command like below

 ansible-playbook  -i inventory.yml -k playbook.yml --extra-vars "java_url=http://download.oracle.com/otn-pub/java/jdk/8u131-b11/d54c1d3a095b4ff2b6607d096fa80163/jdk-8u131-linux-x64.tar.gz"

Best Answer

Even though you didn't actually provide any information on how your code was failing, there are some obvious issues. Ansible is not shell, and you cannot access Ansible variables using shell syntax. You also have different variable names in your code (javaurl) and in your example CLI invocation (java_url). I've arbitrarily chosen to use java_url below.

There are multiple ways to start fixing the existing task.

# Consistently use Jinja
- name: Download Java to Latest Version
  shell: |
    mkdir /opt/java
    cd /opt/java
    wget -c --header "Cookie: oraclelicense=accept-securebackup-cookie" {{ java_url }}
    tar -xzvf {{ (java_url | urlsplit).path | basename }}

# Consistently use shell variables
- name: Download Java to Latest Version
  shell: |
    mkdir /opt/java
    cd /opt/java
    wget -c --header "Cookie: oraclelicense=accept-securebackup-cookie" $java_url
    tar -xzvf ${java_url##*/}
  environment:
    java_url: "{{ java_url }}"

However, instead of fixing your shell script, you should rewrite it using Ansible's builtin features for doing this work.

- name: Create /opt/java
  file:
    dest: /opt/java
    state: directory

- name: Download the Java JDK
  get_url:
    url: "{{ java_url }}"
    dest: /opt/java
    headers:
      Cookie: oraclelicense=accept-securebackup-cookie
  register: result

- name: Extract the Java JDK
  unarchive:
    src: "{{ result.dest }}"
    remote_src: true
    dest: /opt/java