Can't set ansible fact as integer

Viewed 553

I am trying to extract the major distro version (which ansible_facts holds as a string) and store it as an integer for later < or > comparison to an integer. When I do this:

set_fact:
      distromajor: "{{ ansible_facts['distribution_major_version'] | int }}"

I find distromajor holds "7" instead of 7. So later comparisons fail. In fact, the only way I can get it to work is to compare like this:

(distromajor|int >=6) and (distromajor|int <= 8)

Is this expected behaviour? Why can I not save the distro major version as an int?

The closest SO question does not explain why a later integer comparison FAILS without reconverting the distromajor variable to int at time of comparison.

1 Answers

Q: "Is this expected behavior?"

A: Yes. This is the expected behavior, in Ansible.


Q: "Why can I not save the distro major version as an int?"

A: Ansible decided you can't (todo: reference to source code needed). In YAML, there are three basic primitives:

  • mappings (hashes/dictionaries)
  • sequences (arrays/lists)
  • scalars (strings/numbers)

As you can see, the scalars are both strings and numbers. But, for some reason unknown to me, Ansible decided that any "{{ scalar }}" expression can return only string or boolean. For example

    - set_fact:
        distromajor: "{{ ansible_facts['distribution_major_version']|int }}"
    - debug:
        var: distromajor
    - debug:
        msg: "{{ distromajor|type_debug }}"

gives a string despite the explicit conversion to integer, as you've already found out

  distromajor: '20'
  msg: AnsibleUnsafeText
Related