Jinja FAQ: What's the deal with '~'?

~ is the string concatenation operator. It coerces both sides to strings, then concatenates them.

Follow-up question: “Doesn’t + concatenate strings? Why not just use that?”

+ is the addition operator, which is overloaded to mean concatenation when both sides of the expression are strings. While they’re often interchangeable, developing a habit of using the concatenation operator means that you don’t have to worry about or code around the situations where they’re not.

- hosts: localhost
  tasks:
    - name: Addition isn't concatenation
      debug:
        var: 13 + 37

    - name: Concatenation is concatenation
      debug:
        var: 13 ~ 37

    - name: Concatenation handles mixed types
      debug:
        var: 13 ~ '37'

    - name: It's possible to do the coercion manually, but who wants to do that?
      debug:
        var: 13 | string + '37'

    - name: Sadness
      debug:
        var: 13 + '37'
TASK [Addition isn't concatenation] ********************************************
ok: [localhost] => 
    13 + 37: 50

TASK [Concatenation is concatenation] ******************************************
ok: [localhost] => 
    13 ~ 37: '1337'

TASK [Concatenation handles mixed types] ***************************************
ok: [localhost] => 
    13 ~ '37': '1337'

TASK [It's possible to do the coercion manually, but who wants to do that?] ****
ok: [localhost] => 
    13 | string + '37': '1337'

TASK [Sadness] *****************************************************************
[ERROR]: Task failed: Error while resolving `var` expression: Error rendering expression: unsupported operand type(s) for +: 'int' and 'str'

Task failed.
Origin: test.yml:19:7

17         var: 13 | string + '37'
18
19     - name: Sadness
         ^ column 7

<<< caused by >>>

Error while resolving `var` expression: Error rendering expression: unsupported operand type(s) for +: 'int' and 'str'
Origin: test.yml:21:14

19     - name: Sadness
20       debug:
21         var: 13 + '37'
                ^ column 14

fatal: [localhost]: FAILED! => 
    msg: 'Task failed: Error while resolving `var` expression: Error rendering expression:
        unsupported operand type(s) for +: ''int'' and ''str'''