How to read property files into a dictionary via Ansible

2,227 views
Skip to first unread message

Hairy Starcraft

unread,
Apr 4, 2016, 9:05:15 AM4/4/16
to Ansible Project
I currently have a list of property files that I would like to merge into a single dictionary in an Ansible script.

An example file: "alpha.properties":

  name: Alpha
  something_else: some_other_value
  ip: 167.54.97.45
  port: 5001
  other_setting: other_value
  etc...

(I am only interested in the name, ip and port for this dictionary)

Given a variable number of different property files, alpha, beta, charlie, etc... I would like to end up with a dictionary that looks like this:

  {“array”:[

    {“name”:”Alpha”, “ip”:”167.54.97.45”, “port”:”5001”},

    {“name”:”Beta”, “ip”:”176.98.54.27”, “port”:”5042”},

    {“name”:”Charlie”, “ip”:”132.67.54.231”, “port”:”9067”}

  ]}


(I am planning on using this dictionary to template a file, with a for loop inside the templated file)


So far I have managed to make this dictionary only by using some very dodge file manipulation, for example: (Code is not exact but you get the idea)


  property_list has been set to [ "alpha", "beta", "charlie" ]


  # Get Name

  - shell cat {{ item }}.properties | grep "name: " | tail -c4 > {{ item }}.name.temp

    with_items: property_list


  # Get IP

  - shell cat {{ item }}.properties | grep "ip: " | tail -c4 > {{ item }}.ip.temp

    with_items: property_list


  # Get Port

  - shell cat {{ item }}.properties | grep "port: " | tail -c4 > {{ item }}.port.temp

    with_items: property_list


  # Start of Dict File

  - shell echo {\"array\":[ > dict.temp


  # Merge Temp Files

  - shell echo { \"name\": {{ lookup('file', 'alpha.name.temp') }}, \"ip\": {{ lookup('file', 'alpha.ip.temp') }} \"port\": {{ lookup('file', 'alpha.port.temp') }}, > dict.temp

    with_items: property_list


  # End of Dict File (also got rid of extra comma but can't remember how, not really important here)

  - shell echo ]} > dict.temp


  # Get Dictionary

  - set_fact:

      dict_var: "{{ lookup('file', 'dict.temp') }}"


While this does give me the correct Dictionary file, I would love to be able to do this either directly in a yml script using variables/facts, or using a custom module.


I have thought about writing a custom module, but I thought I'd check here first, and leave that as a last resort.


(Due to my older version of Red Hat I am using Ansible 1.9.4, instead of Ansible 2.x, which is why I haven't used the lookup('ini') command... but even this command would not completely solve my problem)


Please let me know if more information is needed. :D

Reply all
Reply to author
Forward
0 new messages