In a role the tasks file can only contain tasks, yet you use the format of a playbook. Remove the hosts and everything else from the top level:
- name: Download the JDK binaries
get_url:
url: https://download.java.net/java/GA/jdk18.0.2.1/db379da656dc47308e138f21b33976fa/1/GPL/openjdk-18.0.2.1_linux-x64_bin.tar.gz
dest: /opt/openjdk-18.0.2.1_linux-x64_bin.tar.gz
- name: Unzip the downloaded file
unarchive:
src: /opt/openjdk-18.0.2.1_linux-x64_bin.tar.gz
dest: /opt
remote_src: yes
- name: Set the JAVA_HOME in /etc/profile file
lineinfile:
path: /etc/profile
state: present
line: "{{ item }}"
with_items:
- 'export JAVA_HOME="/opt/jdk-18.0.2.1"'
- 'export PATH=$PATH:$JAVA_HOME/bin'
- name: Reload /etc/profile file
shell:
cmd: source /etc/profile
The hosts definition belongs in the playbook where you use the role:
hosts: remote_server
become: true
roles:
- java_install
You might want to use some variables instead of fixed paths and filenames though. And that last task is completely useless. Every task starts a new shell where that file is read anyway.
And the unarchive
module accepts URLs. You can reduce that to two tasks:
- name: Unzip JDK
unarchive:
src: https://download.java.net/java/GA/jdk18.0.2.1/db379da656dc47308e138f21b33976fa/1/GPL/openjdk-18.0.2.1_linux-x64_bin.tar.gz
dest: /opt
- name: Set the JAVA_HOME in /etc/profile file
lineinfile:
path: /etc/profile
state: present
line: "{{ item }}"
with_items:
- 'export JAVA_HOME="/opt/jdk-18.0.2.1"'
- 'export PATH=$PATH:$JAVA_HOME/bin'