1

I'm trying to find a way to strip the characters with respect to the ansible_kernel variable. As of now, it outputs something like this:

3.10.0-1127.18.2.el7.x86_64

I just need the first 4 characters (3.10) as I'm looking to write a conditional task for kernel versions that match a specific value.

I attempted to follow the example here but, I just get a hello world as my output:

How to compare kernel (or other) version numbers in Ansible

Here is my simple code:

 - name: check kernel
   hosts: all
   gather_facts: yes
   vars:
      kernel_version: "{{ansible_kernel}}"
  
   tasks:
    
   - debug:
      var: kernel_version
    
   - set_fact: release="{{ kernel_version }}"
 
   - debug:
      var: release
    
   - debug: 
      msg:"Version is {{'release'[:5]}}" //also tried with release.stdout but I get an error

Output of play:

ASK [debug] *******************************************************************
ok: [server] => {
    "kernel_version": "3.10.0-1127.18.2.el7.x86_64"
}
TASK [set_fact] ****************************************************************
ok: [server]
TASK [debug] *******************************************************************
ok: [server] => {
    "release": "3.10.0-1127.18.2.el7.x86_64"
}
TASK [debug] *******************************************************************
ok: [server] => {
    "msg": "Hello world!"

2 Answers2

2

Use split. For example, split the version by dots, select the first two elements, and join them again

    - set_fact:
        ver: "{{ kernel_version.split('.')[:2]|join('.') }}"

gives

  ver: '3.10'

Split by dash '-' and take the first element

    - set_fact:
        ver: "{{ kernel_version.split('-')|first }}"

gives the full version

  ver: 3.10.0

Use Comparing versions to test versions. For example

    - debug:
        msg: Version higher than 3.0.0
      when: ver is version('3.0.0', '>')
    - debug:
        msg: Version lower than 3.0.0
      when: ver is version('3.0.0', '<')

give

TASK [debug] ****
ok: [localhost] =>
  msg: Version higher than 3.0.0

TASK [debug] ****
skipping: [localhost]
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63
0

here is how you could do it. Try:

 - name: check kernel
   hosts: localhost
   gather_facts: yes  
   tasks:
     - debug:
         msg: "Stripped version {{ ansible_kernel[0:4] }}"
     - debug:
         msg: "The version is greater 0.2: {{ ansible_kernel is version_compare('0.2', operator='gt') }}"
     - debug:
         msg: "The version is smaller 0.2: {{ ansible_kernel is version_compare('0.2', operator='lt') }}"

The first one demonstrates how you could get the first 4 characters. It is unsuitable for your purpose, though (what about the version 3.1.4 -> would yield 3.1.

You should go with version_compare (see the other examples). Since ansible 2.9 this is the right syntax

ProfHase85
  • 11,763
  • 7
  • 48
  • 66