Score:-1

Simple Ansible comparison failing when comparing integers

lc flag

I have the following:

- set_fact:
   test_string: "{{ htmlres.content | regex_search('test-([0-9]+)', '\\1') | first}}"

This retrieves 2 which is part of a string contained in the htmlres.content content which is test-2.

So now I'm trying to compare the result of that output and fail the execution if it is not 2, so I tried this:

- name: Fail if test_string is not 2
  fail: msg="Incorrect string. Expected 2, but instead got {{ test_string }}"
  when: test_string != 2

However I've outputted the contents of test_string and I know for a fact that it is 2. Why is it failing?

I've tried adding | string and | int to the end of test_string since my first though is that it would be an issue with type comparison, but that didn't work either.

Thank you.

Zeitounator avatar
fr flag
Please provide a debug output of `test_string`.
br flag
Also ``htmlres.content`` seems to be needed. https://idownvotedbecau.se/nomcve/
Score:3
th flag

Unless jinja2_native is enabled, the result of templating is always a string. You need to take that into account in your comparison.

- name: Fail if test_string is not 2
  fail: msg="Incorrect string. Expected 2, but instead got {{ test_string }}"
  when: test_string | int != 2

or

- name: Fail if test_string is not 2
  fail: msg="Incorrect string. Expected 2, but instead got {{ test_string }}"
  when: test_string != '2'
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.