Parse a variable using a regex and use parsed variable in a "when"

Hi,

I am just starting working with Ansible, and am trying to modify an existing playbook that is used to install MySQL. I need to have it check a Mysql version string, and if it is greater than or equal to a specific version, use that as a conditional in a “when”.

I already have the version string and output it just to see what the version string looks like:

  • name: “Ansible | Print a variable”
    debug:
    msg: “The play_mysql_version is {{ play_mysql_version }}”

The output is:

{
“msg”: “The play_mysql_version is 8.0.28-1.el7”,
“changed”: false,
“_ansible_verbose_always”: true,
“_ansible_no_log”: false
}

i.e., the version string is " 8.0.28-1.el7 ".

Later in the same playbook, I have a step where I want to have a “when” that checks that the “numeric part” of the version string that is in play_mysql_version, i.e. “8.0.28”, is greater than, or equal to, “8.0.28”.

The reason that I need to do this is that, starting at version 8.0.28, there is an additional RPM/dependency that needs to be installed.

So I think I need something (maybe using set_fact and a regex?) to parse the “8.0.28-1.el7” to get the substring “8.0.28”, and then a “when” that compares that parsed substring (“8.0.28”) to “8.0.28”.

Can someone suggest how to do this?

For the parsing part, I have tried using a set_fact and a regex like “^(.*)-1.el7$”, but I think that I am getting the code format wrong.

Also, even if I am able to extract the version, I am not sure how to do the ‘when’.

Thanks,
Jim

See "Comparing versions"
https://docs.ansible.com/ansible/latest/user_guide/playbooks_tests.html#comparing-versions

Test it first, e.g.

    - debug:
        msg: Install additional dependency
      when: play_mysql_version is version ('8.0.28','>=')

That works. One “gotcha” was that I had used to extract out the numeric part of the original version string, using regex_search() but the result from that was an array,so I to use a “first” to get the actual string, which I then used with the version().

Thanks,
Jim