Jinja convert string to integer
<p>I am trying to convert a string that has been parsed using a regex into a number so I can multiply it, using Jinja2. This file is a template to be used within an ansible script.</p>

<p>I have a series of <code>items</code> which all take the form of <code>&lt;word&gt;&lt;number&gt;</code> such as <code>aaa01</code>, <code>aaa141</code>, <code>bbb05</code>.</p>

<p>The idea was to parse the word and number(ignoring leading zeros) and use them later in the template.</p>

<p>I wanted to manipulate the number by multiplication and use it. Below is what I have done so far
```</p>

<pre><code>{% macro get_host_number() -%}
{{ item | regex_replace('^\D*[0]?(\d*)$', '\\1') }}
{%- endmacro %}

{% macro get_host_name() -%}
{{ item | regex_replace('^(\D*)\d*$', '\\1') }}
{%- endmacro %}

{% macro get_host_range(name, number) -%}
{% if name=='aaa' %}
{{ ((number*5)+100) | int | abs }}
{% elif name=='bbb' %}
{{ ((number*5)+200) | int | abs }}
{% else %}
{{ ((number*5)+300) | int | abs }}
{% endif %}
{%- endmacro %}

{% set number = get_host_number() %}
{% set name = get_host_name() %}
{% set value = get_host_range(name, number) %}

Name: {{ name }}
Number: {{ number }}
Type: {{ value }}
</code></pre>

<p>With the above template I am getting an error <code>coercing to Unicode: need string or buffer, int found</code> which i think is telling me it cannot convert the string to integer, however i do not understand why. I have seen examples doing this and working.</p>

<p>You need to cast string to int after regex'ing number:</p>

<pre><code>{% set number = get_host_number() | int %}
</code></pre>

<p>And then there is no need in <code>| int</code> inside <code>get_host_range</code> macro.</p>

python ansible jinja2