Skip to content

Instantly share code, notes, and snippets.

@zanglang
Created January 17, 2017 07:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zanglang/0ed620075cadde5b96ca145767b05b55 to your computer and use it in GitHub Desktop.
Save zanglang/0ed620075cadde5b96ca145767b05b55 to your computer and use it in GitHub Desktop.
Ansible module that takes in a target Java .properties file, and reads it as an Ansible host fact.
#!/usr/bin/env python
"""
Ansible module that takes in a target Java .properties file, and reads it as
an Ansible host fact.
Example:
- read_properties: target=~/dists/cluster/test.properties
register: cluster_props
@author: Jerry Chong <jchong@netbase.com>
"""
from __future__ import print_function
from ansible.module_utils.basic import * # pylint: disable=I0011,W0401,W0614,W0622
import re
def main():
"""Main function"""
module = AnsibleModule(
argument_spec=dict(
target=dict(required=True, aliases=['name', 'dest'])
)
)
params = module.params
target = os.path.expanduser(params['target'])
if not os.path.isfile(target):
module.fail_json(msg="'target' must be a valid file")
# read contents
prop_re = re.compile(r"^(?:#*\s*)(?P<key>[\w.]+)\s*=\s*(?P<val>.*?)?;?\s*$")
props = {}
with open(target, "r") as propfile:
for line in propfile.readlines():
line = line.strip()
match = prop_re.match(line)
if match:
key, val = match.groups()
props[key] = val
module.exit_json(properties=props)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment