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] }}

Using ansible to write directly to postgresql

Lately I've been playing with ansible to create an inventory for network equipment. Actually I want to maintain an inventory and keep it updated.

The concept is to connect to a network device, "get facts" and write the results directly to a database. In this case I've been using postgresql primarily for its "inet" variable type.

Anyway, this is how I did it. I used the shell option in an Ansible task and passed data from "facts" directly to psql command.


- name: Writing facts to database
shell: "psql -U george -d inventory -c 'UPDATE device SET (osversion,osimage,model,hostname,serialnum) = ($${{ansible_net_version}}$$,$${{ ansible_net_image.split('/')[-1] }}$$,$${{ ansible_net_model }}$$,$${{ ansible_net_hostname }}$$,$${{ansible_net_serialnum}}$$) WHERE ipaddress = $${{ inventory_hostname }}$$'"


The best way to make it work seems to be by using "$$" around variables