Ansible and string comparisation for IDs

Posted by ads on Sunday, 2021-05-02
Posted in [Ansible]

Was running in a stupid problem where Ansible (version 2.9.x) throws an error when a variable is defined. The Play:

1
2
3
4
- name: Check if id is defined
  fail:
    msg: "No id defined for {{ inventory_hostname }}!"
  when: id is not defined or id|length == 0

And the error:

TASK [Check if id is defined] *****************************************
fatal: [xxx.xxx.xxx.xxx]: FAILED! => {"msg": "The conditional check 'id is not defined or id|length == 0' failed. The error was: Unexpected templating type error occurred on ({% if id is not defined or id|length == 0 %} True {% else %} False {% endif %}): object of type 'int' has no len()\n\nThe error appears to be in '/path/to/playbook/configuration.yml': line 57, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n    - name: Check if id is defined\n      ^ here\n"}

Ok, it tries to compare an integer, fine. There are two ways to fix this problem:

1: Change the type to a string by updating the inventory:

From:

1
id=1

to:

1
id="1"

But this might have other consequences, as the other parts of the Playbook might depend on this being an integer.

2: Compare as string

1
when: id is not defined or id|string|length == 0

This casts the integer to a string, and then the length() function works.


Categories: [Ansible]

Share: