Tuesday, February 26, 2019

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

No comments:

Post a Comment