Ansible: Compare Zero Integer within a ‘when’ Condition in ‘with_sequence’
Using the Ansible function ‘with_sequence’ within a ‘when’ condition to compare values it may fail when the value is a zero (0) integer. Therefore, you may get the following message:
to count backwards make stride negative
While this makes sense there still may be usecases where you want to evaluate the condition before the sequence is executed. Let’s take a short look on this example.
# This will fail
- name: Download patch files
uri:
url: "https://files.gyptazy.ch/patches/hotfix{{ item }}.tgz"
with_sequence: start=1 end={{ hotfix_max_patchfile }}
when: hotfix_max_patchfile|int > 0
The above written example will immediately fail when ‘hotfix_max_patchfile’ becomes a zero integer. A short and dirty fix would result in defining the ‘hotfix_max_patchfile’ var within an inline condition which gets evaluated by the ‘when’ condition. This could look like:
- name: Download patch files
uri:
url: "https://files.gyptazy.ch/patches/hotfix{{ item }}.tgz"
with_sequence: start=1 end={{ hotfix_max_patchfile|int if hotfix_max_patchfile|int > 0 else 1 }}
when: hotfix_max_patchfile|int > 0
To be honest, this doesn’t look well and takes time to understand. Therefore, let’s write this in a much cleaner way and create sub playbooks and include them as non static ones (included tasks won’t be executed and skipped like the usual static way). As a final result this should be written:
# main.yml:
---
- include: download.yml
static: no
when:
- hotfix_max_patchfile|int > 0
# download.yml:
---
- name: Download patch files
uri:
url: "https://files.gyptazy.ch/patches/hotfix{{ item }}.tgz"
with_sequence: start=1 end={{ hotfix_max_patchfile }}