String does not convert to integer in Ansible Playbook

Viewed 1478

Sorry if this already being asked before, but I can't find any solution that match my problem.

I'm trying to convert the string that I have to convert to an integer:

- hosts: myhost
  vars:
    - variable1: 15
    - variable2: "15"
    - variable3: "{{ variable2 | int }}"

I tried to use variable2 (string) for calculation, so I convert it to int in variable3. But it failed with error message

"Unexpected templating type error occurred on ({{ variable3 + 1 }}): coercing to Unicode: need string or buffer, int found"

So, I tried to use type_debug to find out each type of the 3 variable listed.

  • variable1 is int
  • variable2 is ansibleunicode
  • variable3 is unicode

I don't understand the difference between ansibleunicode and unicode or why it is listed as unicode instead of integer when I already convert it from string to integer using | int.
What should I do?

2 Answers

Try the following.

- hosts: myhost
  vars:
    - variable1: 15
    - variable2: "15"

  tasks:
  - name: test 
    debug: msg="{{ variable2 | int + 1}}"
    delegate_to: localhost

output:

TASK [test] ***********************************************************************************************************************
ok: [remote -> localhost] => {
    "msg": "16"
}

Q: "I still don't understand why variable3 type is Unicode instead of an integer when I already convert it."

A: The output of Jinja is always string. It's a template designer. For example,

    - debug:
        msg: "{{ item }} is {{ item|type_debug }}"
      loop:
        - "{{ var1 }}"
        - "{{ var2 }}"
        - "{{ var1|int }}"
        - "{{ var2|int }}"
      vars:
        var1: 15
        var2: "15"

gives

  msg: 15 is int
  msg: 15 is str
  msg: 15 is str
  msg: 15 is str

Only the first item is recognized as integer. There is no expression in the first item, hence Ansible doesn't call Jinja to evaluate it. Instead, Ansible takes the value of the variable directly. If an expression is evaluated by Jinja the type of the output is always string.

Related