Tuesday, February 26, 2019

Split a long string on a specific delimiter in Ansible playbook

I've been trying to split a long string in an Ansible playbook and there seems to be an easy way to do that.

You have to use the "split" function and specify the delimiter. Depending on which part of the "exploded" string you need, you can use positive or negative values as a parameter.

For example, when trying to get the IOS image from a router you may get something like the following:

"ansible_net_image": "unix:/opt/unetlab/addons/iol/bin/i86bin-linux-l3-adventerprisek9-15.4"

How would you get just the last part of the string in order to store it in a database? Using the split function you specify the delimiter ("/" in this case) and the substring location "-1", counting from the end of the string. 

{{ ansible_net_image.split('/')[-1] }}

In another case how would you get the first part of the string?

{{ ansible_net_image.split('/')[0] }}

No comments:

Post a Comment