yedit.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. #!/usr/bin/env python
  2. # pylint: disable=missing-docstring
  3. # ___ ___ _ _ ___ ___ _ _____ ___ ___
  4. # / __| __| \| | __| _ \ /_\_ _| __| \
  5. # | (_ | _|| .` | _|| / / _ \| | | _|| |) |
  6. # \___|___|_|\_|___|_|_\/_/_\_\_|_|___|___/_ _____
  7. # | \ / _ \ | \| |/ _ \_ _| | __| \_ _|_ _|
  8. # | |) | (_) | | .` | (_) || | | _|| |) | | | |
  9. # |___/ \___/ |_|\_|\___/ |_| |___|___/___| |_|
  10. #
  11. # Copyright 2016 Red Hat, Inc. and/or its affiliates
  12. # and other contributors as indicated by the @author tags.
  13. #
  14. # Licensed under the Apache License, Version 2.0 (the "License");
  15. # you may not use this file except in compliance with the License.
  16. # You may obtain a copy of the License at
  17. #
  18. # http://www.apache.org/licenses/LICENSE-2.0
  19. #
  20. # Unless required by applicable law or agreed to in writing, software
  21. # distributed under the License is distributed on an "AS IS" BASIS,
  22. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  23. # See the License for the specific language governing permissions and
  24. # limitations under the License.
  25. #
  26. # -*- -*- -*- Begin included fragment: lib/import.py -*- -*- -*-
  27. # pylint: disable=wrong-import-order,wrong-import-position,unused-import
  28. from __future__ import print_function # noqa: F401
  29. import copy # noqa: F401
  30. import json # noqa: F401
  31. import os # noqa: F401
  32. import re # noqa: F401
  33. import shutil # noqa: F401
  34. try:
  35. import ruamel.yaml as yaml # noqa: F401
  36. except ImportError:
  37. import yaml # noqa: F401
  38. from ansible.module_utils.basic import AnsibleModule
  39. # -*- -*- -*- End included fragment: lib/import.py -*- -*- -*-
  40. # -*- -*- -*- Begin included fragment: doc/yedit -*- -*- -*-
  41. DOCUMENTATION = '''
  42. ---
  43. module: yedit
  44. short_description: Create, modify, and idempotently manage yaml files.
  45. description:
  46. - Modify yaml files programmatically.
  47. options:
  48. state:
  49. description:
  50. - State represents whether to create, modify, delete, or list yaml
  51. required: true
  52. default: present
  53. choices: ["present", "absent", "list"]
  54. aliases: []
  55. debug:
  56. description:
  57. - Turn on debug information.
  58. required: false
  59. default: false
  60. aliases: []
  61. src:
  62. description:
  63. - The file that is the target of the modifications.
  64. required: false
  65. default: None
  66. aliases: []
  67. content:
  68. description:
  69. - Content represents the yaml content you desire to work with. This
  70. - could be the file contents to write or the inmemory data to modify.
  71. required: false
  72. default: None
  73. aliases: []
  74. content_type:
  75. description:
  76. - The python type of the content parameter.
  77. required: false
  78. default: 'dict'
  79. aliases: []
  80. key:
  81. description:
  82. - The path to the value you wish to modify. Emtpy string means the top of
  83. - the document.
  84. required: false
  85. default: ''
  86. aliases: []
  87. value:
  88. description:
  89. - The incoming value of parameter 'key'.
  90. required: false
  91. default:
  92. aliases: []
  93. value_type:
  94. description:
  95. - The python type of the incoming value.
  96. required: false
  97. default: ''
  98. aliases: []
  99. update:
  100. description:
  101. - Whether the update should be performed on a dict/hash or list/array
  102. - object.
  103. required: false
  104. default: false
  105. aliases: []
  106. append:
  107. description:
  108. - Whether to append to an array/list. When the key does not exist or is
  109. - null, a new array is created. When the key is of a non-list type,
  110. - nothing is done.
  111. required: false
  112. default: false
  113. aliases: []
  114. index:
  115. description:
  116. - Used in conjunction with the update parameter. This will update a
  117. - specific index in an array/list.
  118. required: false
  119. default: false
  120. aliases: []
  121. curr_value:
  122. description:
  123. - Used in conjunction with the update parameter. This is the current
  124. - value of 'key' in the yaml file.
  125. required: false
  126. default: false
  127. aliases: []
  128. curr_value_format:
  129. description:
  130. - Format of the incoming current value.
  131. choices: ["yaml", "json", "str"]
  132. required: false
  133. default: false
  134. aliases: []
  135. backup:
  136. description:
  137. - Whether to make a backup copy of the current file when performing an
  138. - edit.
  139. required: false
  140. default: true
  141. aliases: []
  142. separator:
  143. description:
  144. - The separator being used when parsing strings.
  145. required: false
  146. default: '.'
  147. aliases: []
  148. author:
  149. - "Kenny Woodson <kwoodson@redhat.com>"
  150. extends_documentation_fragment: []
  151. '''
  152. EXAMPLES = '''
  153. # Simple insert of key, value
  154. - name: insert simple key, value
  155. yedit:
  156. src: somefile.yml
  157. key: test
  158. value: somevalue
  159. state: present
  160. # Results:
  161. # test: somevalue
  162. # Multilevel insert of key, value
  163. - name: insert simple key, value
  164. yedit:
  165. src: somefile.yml
  166. key: a#b#c
  167. value: d
  168. state: present
  169. # Results:
  170. # a:
  171. # b:
  172. # c: d
  173. '''
  174. # -*- -*- -*- End included fragment: doc/yedit -*- -*- -*-
  175. # -*- -*- -*- Begin included fragment: class/yedit.py -*- -*- -*-
  176. # pylint: disable=undefined-variable,missing-docstring
  177. # noqa: E301,E302
  178. class YeditException(Exception):
  179. ''' Exception class for Yedit '''
  180. pass
  181. # pylint: disable=too-many-public-methods
  182. class Yedit(object):
  183. ''' Class to modify yaml files '''
  184. re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$"
  185. re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z%s/_-]+)"
  186. com_sep = set(['.', '#', '|', ':'])
  187. # pylint: disable=too-many-arguments
  188. def __init__(self,
  189. filename=None,
  190. content=None,
  191. content_type='yaml',
  192. separator='.',
  193. backup=False):
  194. self.content = content
  195. self._separator = separator
  196. self.filename = filename
  197. self.__yaml_dict = content
  198. self.content_type = content_type
  199. self.backup = backup
  200. self.load(content_type=self.content_type)
  201. if self.__yaml_dict is None:
  202. self.__yaml_dict = {}
  203. @property
  204. def separator(self):
  205. ''' getter method for yaml_dict '''
  206. return self._separator
  207. @separator.setter
  208. def separator(self):
  209. ''' getter method for yaml_dict '''
  210. return self._separator
  211. @property
  212. def yaml_dict(self):
  213. ''' getter method for yaml_dict '''
  214. return self.__yaml_dict
  215. @yaml_dict.setter
  216. def yaml_dict(self, value):
  217. ''' setter method for yaml_dict '''
  218. self.__yaml_dict = value
  219. @staticmethod
  220. def parse_key(key, sep='.'):
  221. '''parse the key allowing the appropriate separator'''
  222. common_separators = list(Yedit.com_sep - set([sep]))
  223. return re.findall(Yedit.re_key % ''.join(common_separators), key)
  224. @staticmethod
  225. def valid_key(key, sep='.'):
  226. '''validate the incoming key'''
  227. common_separators = list(Yedit.com_sep - set([sep]))
  228. if not re.match(Yedit.re_valid_key % ''.join(common_separators), key):
  229. return False
  230. return True
  231. @staticmethod
  232. def remove_entry(data, key, sep='.'):
  233. ''' remove data at location key '''
  234. if key == '' and isinstance(data, dict):
  235. data.clear()
  236. return True
  237. elif key == '' and isinstance(data, list):
  238. del data[:]
  239. return True
  240. if not (key and Yedit.valid_key(key, sep)) and \
  241. isinstance(data, (list, dict)):
  242. return None
  243. key_indexes = Yedit.parse_key(key, sep)
  244. for arr_ind, dict_key in key_indexes[:-1]:
  245. if dict_key and isinstance(data, dict):
  246. data = data.get(dict_key, None)
  247. elif (arr_ind and isinstance(data, list) and
  248. int(arr_ind) <= len(data) - 1):
  249. data = data[int(arr_ind)]
  250. else:
  251. return None
  252. # process last index for remove
  253. # expected list entry
  254. if key_indexes[-1][0]:
  255. if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  256. del data[int(key_indexes[-1][0])]
  257. return True
  258. # expected dict entry
  259. elif key_indexes[-1][1]:
  260. if isinstance(data, dict):
  261. del data[key_indexes[-1][1]]
  262. return True
  263. @staticmethod
  264. def add_entry(data, key, item=None, sep='.'):
  265. ''' Get an item from a dictionary with key notation a.b.c
  266. d = {'a': {'b': 'c'}}}
  267. key = a#b
  268. return c
  269. '''
  270. if key == '':
  271. pass
  272. elif (not (key and Yedit.valid_key(key, sep)) and
  273. isinstance(data, (list, dict))):
  274. return None
  275. key_indexes = Yedit.parse_key(key, sep)
  276. for arr_ind, dict_key in key_indexes[:-1]:
  277. if dict_key:
  278. if isinstance(data, dict) and dict_key in data and data[dict_key]: # noqa: E501
  279. data = data[dict_key]
  280. continue
  281. elif data and not isinstance(data, dict):
  282. raise YeditException("Unexpected item type found while going through key " +
  283. "path: {} (at key: {})".format(key, dict_key))
  284. data[dict_key] = {}
  285. data = data[dict_key]
  286. elif (arr_ind and isinstance(data, list) and
  287. int(arr_ind) <= len(data) - 1):
  288. data = data[int(arr_ind)]
  289. else:
  290. raise YeditException("Unexpected item type found while going through key path: {}".format(key))
  291. if key == '':
  292. data = item
  293. # process last index for add
  294. # expected list entry
  295. elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: # noqa: E501
  296. data[int(key_indexes[-1][0])] = item
  297. # expected dict entry
  298. elif key_indexes[-1][1] and isinstance(data, dict):
  299. data[key_indexes[-1][1]] = item
  300. # didn't add/update to an existing list, nor add/update key to a dict
  301. # so we must have been provided some syntax like a.b.c[<int>] = "data" for a
  302. # non-existent array
  303. else:
  304. raise YeditException("Error adding to object at path: {}".format(key))
  305. return data
  306. @staticmethod
  307. def get_entry(data, key, sep='.'):
  308. ''' Get an item from a dictionary with key notation a.b.c
  309. d = {'a': {'b': 'c'}}}
  310. key = a.b
  311. return c
  312. '''
  313. if key == '':
  314. pass
  315. elif (not (key and Yedit.valid_key(key, sep)) and
  316. isinstance(data, (list, dict))):
  317. return None
  318. key_indexes = Yedit.parse_key(key, sep)
  319. for arr_ind, dict_key in key_indexes:
  320. if dict_key and isinstance(data, dict):
  321. data = data.get(dict_key, None)
  322. elif (arr_ind and isinstance(data, list) and
  323. int(arr_ind) <= len(data) - 1):
  324. data = data[int(arr_ind)]
  325. else:
  326. return None
  327. return data
  328. @staticmethod
  329. def _write(filename, contents):
  330. ''' Actually write the file contents to disk. This helps with mocking. '''
  331. tmp_filename = filename + '.yedit'
  332. with open(tmp_filename, 'w') as yfd:
  333. yfd.write(contents)
  334. os.rename(tmp_filename, filename)
  335. def write(self):
  336. ''' write to file '''
  337. if not self.filename:
  338. raise YeditException('Please specify a filename.')
  339. if self.backup and self.file_exists():
  340. shutil.copy(self.filename, self.filename + '.orig')
  341. # Try to set format attributes if supported
  342. try:
  343. self.yaml_dict.fa.set_block_style()
  344. except AttributeError:
  345. pass
  346. # Try to use RoundTripDumper if supported.
  347. try:
  348. Yedit._write(self.filename, yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper))
  349. except AttributeError:
  350. Yedit._write(self.filename, yaml.safe_dump(self.yaml_dict, default_flow_style=False))
  351. return (True, self.yaml_dict)
  352. def read(self):
  353. ''' read from file '''
  354. # check if it exists
  355. if self.filename is None or not self.file_exists():
  356. return None
  357. contents = None
  358. with open(self.filename) as yfd:
  359. contents = yfd.read()
  360. return contents
  361. def file_exists(self):
  362. ''' return whether file exists '''
  363. if os.path.exists(self.filename):
  364. return True
  365. return False
  366. def load(self, content_type='yaml'):
  367. ''' return yaml file '''
  368. contents = self.read()
  369. if not contents and not self.content:
  370. return None
  371. if self.content:
  372. if isinstance(self.content, dict):
  373. self.yaml_dict = self.content
  374. return self.yaml_dict
  375. elif isinstance(self.content, str):
  376. contents = self.content
  377. # check if it is yaml
  378. try:
  379. if content_type == 'yaml' and contents:
  380. # Try to set format attributes if supported
  381. try:
  382. self.yaml_dict.fa.set_block_style()
  383. except AttributeError:
  384. pass
  385. # Try to use RoundTripLoader if supported.
  386. try:
  387. self.yaml_dict = yaml.safe_load(contents, yaml.RoundTripLoader)
  388. except AttributeError:
  389. self.yaml_dict = yaml.safe_load(contents)
  390. # Try to set format attributes if supported
  391. try:
  392. self.yaml_dict.fa.set_block_style()
  393. except AttributeError:
  394. pass
  395. elif content_type == 'json' and contents:
  396. self.yaml_dict = json.loads(contents)
  397. except yaml.YAMLError as err:
  398. # Error loading yaml or json
  399. raise YeditException('Problem with loading yaml file. %s' % err)
  400. return self.yaml_dict
  401. def get(self, key):
  402. ''' get a specified key'''
  403. try:
  404. entry = Yedit.get_entry(self.yaml_dict, key, self.separator)
  405. except KeyError:
  406. entry = None
  407. return entry
  408. def pop(self, path, key_or_item):
  409. ''' remove a key, value pair from a dict or an item for a list'''
  410. try:
  411. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  412. except KeyError:
  413. entry = None
  414. if entry is None:
  415. return (False, self.yaml_dict)
  416. if isinstance(entry, dict):
  417. # AUDIT:maybe-no-member makes sense due to fuzzy types
  418. # pylint: disable=maybe-no-member
  419. if key_or_item in entry:
  420. entry.pop(key_or_item)
  421. return (True, self.yaml_dict)
  422. return (False, self.yaml_dict)
  423. elif isinstance(entry, list):
  424. # AUDIT:maybe-no-member makes sense due to fuzzy types
  425. # pylint: disable=maybe-no-member
  426. ind = None
  427. try:
  428. ind = entry.index(key_or_item)
  429. except ValueError:
  430. return (False, self.yaml_dict)
  431. entry.pop(ind)
  432. return (True, self.yaml_dict)
  433. return (False, self.yaml_dict)
  434. def delete(self, path):
  435. ''' remove path from a dict'''
  436. try:
  437. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  438. except KeyError:
  439. entry = None
  440. if entry is None:
  441. return (False, self.yaml_dict)
  442. result = Yedit.remove_entry(self.yaml_dict, path, self.separator)
  443. if not result:
  444. return (False, self.yaml_dict)
  445. return (True, self.yaml_dict)
  446. def exists(self, path, value):
  447. ''' check if value exists at path'''
  448. try:
  449. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  450. except KeyError:
  451. entry = None
  452. if isinstance(entry, list):
  453. if value in entry:
  454. return True
  455. return False
  456. elif isinstance(entry, dict):
  457. if isinstance(value, dict):
  458. rval = False
  459. for key, val in value.items():
  460. if entry[key] != val:
  461. rval = False
  462. break
  463. else:
  464. rval = True
  465. return rval
  466. return value in entry
  467. return entry == value
  468. def append(self, path, value):
  469. '''append value to a list'''
  470. try:
  471. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  472. except KeyError:
  473. entry = None
  474. if entry is None:
  475. self.put(path, [])
  476. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  477. if not isinstance(entry, list):
  478. return (False, self.yaml_dict)
  479. # AUDIT:maybe-no-member makes sense due to loading data from
  480. # a serialized format.
  481. # pylint: disable=maybe-no-member
  482. entry.append(value)
  483. return (True, self.yaml_dict)
  484. # pylint: disable=too-many-arguments
  485. def update(self, path, value, index=None, curr_value=None):
  486. ''' put path, value into a dict '''
  487. try:
  488. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  489. except KeyError:
  490. entry = None
  491. if isinstance(entry, dict):
  492. # AUDIT:maybe-no-member makes sense due to fuzzy types
  493. # pylint: disable=maybe-no-member
  494. if not isinstance(value, dict):
  495. raise YeditException('Cannot replace key, value entry in ' +
  496. 'dict with non-dict type. value=[%s] [%s]' % (value, type(value))) # noqa: E501
  497. entry.update(value)
  498. return (True, self.yaml_dict)
  499. elif isinstance(entry, list):
  500. # AUDIT:maybe-no-member makes sense due to fuzzy types
  501. # pylint: disable=maybe-no-member
  502. ind = None
  503. if curr_value:
  504. try:
  505. ind = entry.index(curr_value)
  506. except ValueError:
  507. return (False, self.yaml_dict)
  508. elif index is not None:
  509. ind = index
  510. if ind is not None and entry[ind] != value:
  511. entry[ind] = value
  512. return (True, self.yaml_dict)
  513. # see if it exists in the list
  514. try:
  515. ind = entry.index(value)
  516. except ValueError:
  517. # doesn't exist, append it
  518. entry.append(value)
  519. return (True, self.yaml_dict)
  520. # already exists, return
  521. if ind is not None:
  522. return (False, self.yaml_dict)
  523. return (False, self.yaml_dict)
  524. def put(self, path, value):
  525. ''' put path, value into a dict '''
  526. try:
  527. entry = Yedit.get_entry(self.yaml_dict, path, self.separator)
  528. except KeyError:
  529. entry = None
  530. if entry == value:
  531. return (False, self.yaml_dict)
  532. # deepcopy didn't work
  533. # Try to use ruamel.yaml and fallback to pyyaml
  534. try:
  535. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  536. default_flow_style=False),
  537. yaml.RoundTripLoader)
  538. except AttributeError:
  539. tmp_copy = copy.deepcopy(self.yaml_dict)
  540. # set the format attributes if available
  541. try:
  542. tmp_copy.fa.set_block_style()
  543. except AttributeError:
  544. pass
  545. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  546. if not result:
  547. return (False, self.yaml_dict)
  548. self.yaml_dict = tmp_copy
  549. return (True, self.yaml_dict)
  550. def create(self, path, value):
  551. ''' create a yaml file '''
  552. if not self.file_exists():
  553. # deepcopy didn't work
  554. # Try to use ruamel.yaml and fallback to pyyaml
  555. try:
  556. tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict,
  557. default_flow_style=False),
  558. yaml.RoundTripLoader)
  559. except AttributeError:
  560. tmp_copy = copy.deepcopy(self.yaml_dict)
  561. # set the format attributes if available
  562. try:
  563. tmp_copy.fa.set_block_style()
  564. except AttributeError:
  565. pass
  566. result = Yedit.add_entry(tmp_copy, path, value, self.separator)
  567. if result:
  568. self.yaml_dict = tmp_copy
  569. return (True, self.yaml_dict)
  570. return (False, self.yaml_dict)
  571. @staticmethod
  572. def get_curr_value(invalue, val_type):
  573. '''return the current value'''
  574. if invalue is None:
  575. return None
  576. curr_value = invalue
  577. if val_type == 'yaml':
  578. curr_value = yaml.load(invalue)
  579. elif val_type == 'json':
  580. curr_value = json.loads(invalue)
  581. return curr_value
  582. @staticmethod
  583. def parse_value(inc_value, vtype=''):
  584. '''determine value type passed'''
  585. true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE',
  586. 'on', 'On', 'ON', ]
  587. false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE',
  588. 'off', 'Off', 'OFF']
  589. # It came in as a string but you didn't specify value_type as string
  590. # we will convert to bool if it matches any of the above cases
  591. if isinstance(inc_value, str) and 'bool' in vtype:
  592. if inc_value not in true_bools and inc_value not in false_bools:
  593. raise YeditException('Not a boolean type. str=[%s] vtype=[%s]'
  594. % (inc_value, vtype))
  595. elif isinstance(inc_value, bool) and 'str' in vtype:
  596. inc_value = str(inc_value)
  597. # If vtype is not str then go ahead and attempt to yaml load it.
  598. if isinstance(inc_value, str) and 'str' not in vtype:
  599. try:
  600. inc_value = yaml.load(inc_value)
  601. except Exception:
  602. raise YeditException('Could not determine type of incoming ' +
  603. 'value. value=[%s] vtype=[%s]'
  604. % (type(inc_value), vtype))
  605. return inc_value
  606. # pylint: disable=too-many-return-statements,too-many-branches
  607. @staticmethod
  608. def run_ansible(module):
  609. '''perform the idempotent crud operations'''
  610. yamlfile = Yedit(filename=module.params['src'],
  611. backup=module.params['backup'],
  612. separator=module.params['separator'])
  613. if module.params['src']:
  614. rval = yamlfile.load()
  615. if yamlfile.yaml_dict is None and \
  616. module.params['state'] != 'present':
  617. return {'failed': True,
  618. 'msg': 'Error opening file [%s]. Verify that the ' +
  619. 'file exists, that it is has correct' +
  620. ' permissions, and is valid yaml.'}
  621. if module.params['state'] == 'list':
  622. if module.params['content']:
  623. content = Yedit.parse_value(module.params['content'],
  624. module.params['content_type'])
  625. yamlfile.yaml_dict = content
  626. if module.params['key']:
  627. rval = yamlfile.get(module.params['key']) or {}
  628. return {'changed': False, 'result': rval, 'state': "list"}
  629. elif module.params['state'] == 'absent':
  630. if module.params['content']:
  631. content = Yedit.parse_value(module.params['content'],
  632. module.params['content_type'])
  633. yamlfile.yaml_dict = content
  634. if module.params['update']:
  635. rval = yamlfile.pop(module.params['key'],
  636. module.params['value'])
  637. else:
  638. rval = yamlfile.delete(module.params['key'])
  639. if rval[0] and module.params['src']:
  640. yamlfile.write()
  641. return {'changed': rval[0], 'result': rval[1], 'state': "absent"}
  642. elif module.params['state'] == 'present':
  643. # check if content is different than what is in the file
  644. if module.params['content']:
  645. content = Yedit.parse_value(module.params['content'],
  646. module.params['content_type'])
  647. # We had no edits to make and the contents are the same
  648. if yamlfile.yaml_dict == content and \
  649. module.params['value'] is None:
  650. return {'changed': False,
  651. 'result': yamlfile.yaml_dict,
  652. 'state': "present"}
  653. yamlfile.yaml_dict = content
  654. # we were passed a value; parse it
  655. if module.params['value']:
  656. value = Yedit.parse_value(module.params['value'],
  657. module.params['value_type'])
  658. key = module.params['key']
  659. if module.params['update']:
  660. # pylint: disable=line-too-long
  661. curr_value = Yedit.get_curr_value(Yedit.parse_value(module.params['curr_value']), # noqa: E501
  662. module.params['curr_value_format']) # noqa: E501
  663. rval = yamlfile.update(key, value, module.params['index'], curr_value) # noqa: E501
  664. elif module.params['append']:
  665. rval = yamlfile.append(key, value)
  666. else:
  667. rval = yamlfile.put(key, value)
  668. if rval[0] and module.params['src']:
  669. yamlfile.write()
  670. return {'changed': rval[0],
  671. 'result': rval[1], 'state': "present"}
  672. # no edits to make
  673. if module.params['src']:
  674. # pylint: disable=redefined-variable-type
  675. rval = yamlfile.write()
  676. return {'changed': rval[0],
  677. 'result': rval[1],
  678. 'state': "present"}
  679. return {'failed': True, 'msg': 'Unkown state passed'}
  680. # -*- -*- -*- End included fragment: class/yedit.py -*- -*- -*-
  681. # -*- -*- -*- Begin included fragment: ansible/yedit.py -*- -*- -*-
  682. # pylint: disable=too-many-branches
  683. def main():
  684. ''' ansible oc module for secrets '''
  685. module = AnsibleModule(
  686. argument_spec=dict(
  687. state=dict(default='present', type='str',
  688. choices=['present', 'absent', 'list']),
  689. debug=dict(default=False, type='bool'),
  690. src=dict(default=None, type='str'),
  691. content=dict(default=None),
  692. content_type=dict(default='dict', choices=['dict']),
  693. key=dict(default='', type='str'),
  694. value=dict(),
  695. value_type=dict(default='', type='str'),
  696. update=dict(default=False, type='bool'),
  697. append=dict(default=False, type='bool'),
  698. index=dict(default=None, type='int'),
  699. curr_value=dict(default=None, type='str'),
  700. curr_value_format=dict(default='yaml',
  701. choices=['yaml', 'json', 'str'],
  702. type='str'),
  703. backup=dict(default=True, type='bool'),
  704. separator=dict(default='.', type='str'),
  705. ),
  706. mutually_exclusive=[["curr_value", "index"], ['update', "append"]],
  707. required_one_of=[["content", "src"]],
  708. )
  709. rval = Yedit.run_ansible(module)
  710. if 'failed' in rval and rval['failed']:
  711. module.fail_json(**rval)
  712. module.exit_json(**rval)
  713. if __name__ == '__main__':
  714. main()
  715. # -*- -*- -*- End included fragment: ansible/yedit.py -*- -*- -*-