Alternatives are a decent way in linux to set different path executables for a certain program. I'd guess that the most commonly used alternatives on modern systems are java and python.
For this example, I'll use three different versions of java installed on a el8 system and use the 'community.general.alternatives' module to select the executable behind '/usr/bin/java'.
First, we need to define some variables and ensure java is installed:
- name: deploy java
hosts: test
user: root
become: false
gather_facts: true
collections:
- community.general
vars:
java_selected_version: "{{ java_future_version }}"
java_legacy_version: '1.8.0'
java_current_version: '11'
java_future_version: '17'
tasks:
- name: install java packages
ansible.builtin.package:
name:
- "java-{{ java_legacy_version }}-openjdk"
- "java-{{ java_legacy_version }}-openjdk-headless"
- "java-{{ java_current_version }}-openjdk"
- "java-{{ java_current_version }}-openjdk-headless"
- "java-{{ java_future_version }}-openjdk"
- "java-{{ java_future_version }}-openjdk-headless"
state: present
Next, we need a task to get the binary path for the selected java version:
- name: get java binary path
ansible.builtin.shell:
executable: /usr/bin/bash
cmd: "rpm -ql java-{{ openjdk_version }}-openjdk-headless | grep -iE '\\/usr\\/lib\\/.*\\/bin\\/java$'"
register: java_binary_path
changed_when: false
For the last task, we need to set the alternative and use the value 'selected' as the value for the state attribute. Using 'present' here will just ensure that there's a alternative named 'java' present but not ensure that the selected version is set as the alternative:
- name: set java alternative path
community.general.alternatives:
name: java
path: "{{ java_binary_path['stdout'] }}"
link: /usr/bin/java
state: selected
Here's the playbook pieced together:
---
- name: deploy java
hosts: test
user: root
become: false
gather_facts: true
collections:
- community.general
vars:
java_selected_version: "{{ java_current_version }}"
java_legacy_version: '1.8.0'
java_current_version: '11'
java_future_version: '17'
tasks:
- name: install java packages
ansible.builtin.package:
name:
- "java-{{ java_legacy_version }}-openjdk"
- "java-{{ java_legacy_version }}-openjdk-headless"
- "java-{{ java_current_version }}-openjdk"
- "java-{{ java_current_version }}-openjdk-headless"
- "java-{{ java_future_version }}-openjdk"
- "java-{{ java_future_version }}-openjdk-headless"
state: present
- name: get java path
ansible.builtin.shell:
executable: /usr/bin/bash
cmd: "rpm -ql java-{{ java_selected_version }}-openjdk-headless | grep -iE 'bin\/java$'"
register: java_binary_path
changed_when: false
- name: set java alternative path
community.general.alternatives:
name: java
path: "{{ java_binary_path['stdout'] }}"
link: /usr/bin/java
state: selected
...
Feel free to comment and / or suggest a topic.
Comments
Post a Comment