Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

splitting string by whitespace and then joining it again in ansible/jinja2

Tags:

ansible

jinja2

I'm trying to "cleanup" whitespaces in a variable in Ansible (ansible-2.1.1.0-1.fc24.noarch) playbook and I though I'll first split() it and then join(' ') again. For some reason that approach is giving me error below :-/

---
- hosts: all
  remote_user: root
  vars:
    mytext: |
      hello
      there how   are
      you?
  tasks:
    - debug:
        msg: "{{ mytext }}"
    - debug:
        msg: "{{ mytext.split() }}"
    - debug:
        msg: "{{ mytext.split().join(' ') }}"
...

Gives me:

TASK [debug] *******************************************************************
ok: [192.168.122.193] => {
    "msg": "hello\nthere how   are\nyou?\n"
}

TASK [debug] *******************************************************************
ok: [192.168.122.193] => {
    "msg": [
        "hello", 
        "there", 
        "how", 
        "are", 
        "you?"
    ]
}

TASK [debug] *******************************************************************
fatal: [192.168.122.193]: FAILED! => {"failed": true, "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'list object' has no attribute 'join'\n\nThe error appears to have been in '.../tests.yaml': line 15, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n        msg: \"{{ mytext.split() }}\"\n    - debug:\n      ^ here\n"}

Any idea on what I'm doing wrong? It says the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'list object' has no attribute 'join', but according to useful filters docs, it should work.

like image 510
jhutar Avatar asked Sep 30 '16 14:09

jhutar


1 Answers

You should use pipe to apply a filter:

- debug:
    msg: "{{ mytext.split() | join(' ') }}"

In this example split() is a Python method of string object. So it's a bit hackery.
And join(' ') is a Jinja2 filter that concatenates a list into string.

By calling mytext.split().join(' ') you get error, because there is no join method for lists in Python.
There is join method for string in Python and you can call ' '.join(mytext.split()), but it will be a double hack.

like image 88
Konstantin Suvorov Avatar answered Nov 07 '22 19:11

Konstantin Suvorov