| Dmitry Ukov | f58264b | 2017-04-20 23:08:42 +0200 | [diff] [blame] | 1 | #!/usr/bin/env python | 
 | 2 | ''' | 
 | 3 | Management of policy.json | 
 | 4 | ========================= | 
 | 5 |  | 
 | 6 | Merge user defined hash to policy.json | 
 | 7 | -------------------------------------- | 
 | 8 |  | 
 | 9 | .. code-block:: yaml | 
 | 10 |  | 
 | 11 | /etc/keystone/policy.json: | 
 | 12 |   keystone_policy.present: | 
 | 13 |     - override_data: | 
 | 14 |         override_key: override_value | 
 | 15 |     - formatter: json | 
 | 16 |  | 
 | 17 | ''' | 
 | 18 | import logging | 
 | 19 | import json | 
 | 20 |  | 
 | 21 | log = logging.getLogger(__name__) | 
 | 22 |  | 
 | 23 | JSON_LOCATION = '/etc/keystone/policy.json' | 
 | 24 |  | 
 | 25 |  | 
 | 26 | def _deep_merge(dct, merge_dct): | 
 | 27 |     for k, v in merge_dct.iteritems(): | 
 | 28 |         if (k in dct and isinstance(dct[k], dict)): | 
 | 29 |             _deep_merge(dct[k], merge_dct[k]) | 
 | 30 |         else: | 
 | 31 |             dct[k] = merge_dct[k] | 
 | 32 |  | 
 | 33 |  | 
 | 34 | def present(name, override_data={}, **kwargs): | 
 | 35 |     ''' | 
 | 36 |     Ensures that given key present in policy.json file. This is a wrapper | 
 | 37 |     around file.serialize state with additional argument: override_data. | 
 | 38 |     Rest parameters of file.serialize can be safely used as well. | 
 | 39 |     Function reads contents of existing policy.json file into a python | 
 | 40 |     dictionary. User defined data populated to this dictionary using deep | 
 | 41 |     merge procedure. | 
 | 42 |  | 
 | 43 |     :param name:          Name of the resource | 
 | 44 |     :param override_data: User defined data with overrides | 
 | 45 |     ''' | 
 | 46 |     with open(JSON_LOCATION) as policy_json: | 
 | 47 |         json_content = json.load(policy_json) | 
 | 48 |  | 
 | 49 |     _deep_merge(json_content, override_data) | 
 | 50 |  | 
 | 51 |     kwargs['dataset'] = json_content | 
 | 52 |     ret = __states__['file.serialize']('/etc/keystone/policy.json', **kwargs) | 
 | 53 |     return ret |