Search code examples
ansibleansible-template

Ansible string split


I have a split function in ansible based on a delimiter. But only want to get the first occurance of the delimiter string and the rest as the second string.

string: "hello=abcd=def=asd"
string1= string.split("=")[0]
string2= string.split("=)[1..n] (This is what i missing)

How can i achieve this in ansible with string.split?


Solution

  • Q: "Get the first occurrence of the delimiter string and the rest as the second string."

    A: Join the rest of the string again

      arr: "{{ string.split('=') }}"
      string1: "{{ arr[0] }}"
      string2: "{{ arr[1:] | join('=') }}"
    

    Optionally, set the maxsplit parameter to 1

      arr: "{{ string.split('=', 1) }}"
      string1: "{{ arr.0 }}"
      string2: "{{ arr.1 }}"
    

    Both options give the same result

      string1: hello
      string2: abcd=def=asd