Vini
Vini

Reputation: 2134

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?

Upvotes: 5

Views: 24330

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68044

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

Upvotes: 10

Related Questions